SQL Group By函数(列) - 现在无法选择该列

Mar*_*ada 7 sql oracle aggregate-functions ora-00979

我在Oracle Express中使用了HR员工架构,我想选择在特定年份雇用的员工.

  SELECT hire_date, 
         COUNT(*)
    FROM employees empl
GROUP BY SUBSTR(hire_date, -4)
ORDER BY empl.hire_date;
Run Code Online (Sandbox Code Playgroud)

hire_date列的格式为"1/1/2011",所以我想通过提取最后四个字符对它们进行分组.

问题是,我遇到了以下错误

ORA-00979: not a GROUP BY expression
00979. 00000 -  "not a GROUP BY expression"
*Cause:    
*Action:
Error at Line: 1 Column: 7
Run Code Online (Sandbox Code Playgroud)

这不可能吗?

pax*_*blo 9

hire_date如果仅按最后四位数分组,则无法选择完整.想想如果你有两行会发生什么:

hire_date
=========
01/01/2001
02/02/2001
Run Code Online (Sandbox Code Playgroud)

在分组时生成的单行中,应该hire_date是什么?

选择的每个列必须是分组列或聚合列.换句话说,尝试:

select substr(hire_date,-4), count(*)
from employees
group by substr(hire_date,-4)
order by empl.hire_date;
Run Code Online (Sandbox Code Playgroud)

我应该提到,每行功能在缩放方面都是出了名的不好.如果您想要处理很多年份,您应该考虑将其拆分为自己的列.这可能会大大提高性能,但衡量,不要猜!

并且,正如其他人在评论中提到的那样,substr可能不是最好的解决方案,因为这可能取决于区域设置(如:日期可能被格式化为YYYY-MM-DD不适合的日期substring).

使用类似to_char(hire_date,'YYYY')extract (year from hire_date)更强大的东西可能更好.

  • 而且你还应该提到在日期上做一个SUBSTR是一个非常糟糕的主意(正如a_horse_with_no_name已经提到的那样)."group by extract(来自hire_date的年份)"是要走的路. (4认同)

sch*_*rik 7

您也可以截断hiredate列

select trunc(hiredate, 'yyyy'), count(*) 
from employee
group by trunc(hiredate, 'yyyy')
Run Code Online (Sandbox Code Playgroud)