7

我在 Oracle Express 中使用了 HR 员工模式,我想选择在特定年份聘用的员工。

  SELECT hire_date, 
         COUNT(*)
    FROM employees empl
GROUP BY SUBSTR(hire_date, -4)
ORDER BY empl.hire_date;

hir_date 列的格式为“2011 年 1 月 1 日”,所以我想通过提取最后四个字符来对它们进行分组。

问题是,我遇到以下错误

ORA-00979: not a GROUP BY expression
00979. 00000 -  "not a GROUP BY expression"
*Cause:    
*Action:
Error at Line: 1 Column: 7

这不可能吗?

4

4 回答 4

9

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

hire_date
=========
01/01/2001
02/02/2001

在您对它们进行分组时生成的单行中,应该hire_date是什么?

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

select substr(hire_date,-4), count(*)
from employees
group by substr(hire_date,-4)
order by empl.hire_date;

我应该提到每行函数在扩展方面是出了名的糟糕。如果您想大量处理年份,则应考虑将其拆分为自己的列。这可能会大大提高性能,但要衡量,不要猜测!

而且,正如其他人在评论中提到的那样,substr这可能不是最好的解决方案,因为这可能取决于语言环境(例如:日期可能被格式化为YYYY-MM-DD不适合 的格式substring)。

使用类似to_char(hire_date,'YYYY')extract (year from hire_date)应该更健壮的东西可能会更好。

于 2011-05-26T07:43:22.977 回答
7

你也可以截断hiredate列

select trunc(hiredate, 'yyyy'), count(*) 
from employee
group by trunc(hiredate, 'yyyy')
于 2011-05-26T09:13:14.203 回答
1

如果你想按他们被雇用的年份分组员工在使用中

select to_char(hiredate,'yyyy'),count(*) 
from employee
group by to_char(hiredate,'yyyy')
于 2011-05-26T07:46:04.760 回答
0

您只能在查询部分使用GROUP BY条件或聚合函数(MIN, MAX, AVG等)。这有效:SELECTGROUP BY

select substr(hire_date,-4), count(*)
from employees empl
group by substr(hire_date,-4)
order by substr(hire_date,-4);
于 2011-05-26T07:41:45.440 回答