我有一张EMPLOYEES表:
employee_id(1) hire_date(15-2-2001)
employee_id(2) hire_date(2-2-1999)
employee_id(3) hire_date(11-2-2003)
employee_id(4) hire_date(6-7-2001)
我希望显示雇用的员工人数最多的年份,每月雇用的员工人数。 我试过这个:
select extract (year from hire_date)
from employees
where max(count(employee_id))=count(employee_id)
order by extract (year from hire_date);
我继续得到" ORA-00934:这里不允许使用群组功能"
我做错了什么?
我使用的是ORACLE 10g Express。
答案 0 :(得分:2)
我们的想法是,您可以使用聚合和窗口函数来按月和年份获取总计。然后,您可以使用row_number()
或dense_rank()
选择最大的。
select ym.*
from (select ym.*, dense_rank() over (order by year_cnt, year) as seqnum
from (select extract(year from hire_date) as yyyy,
extract(month from hire_date) as mm,
count(*) as cnt,
sum(count(*)) over (partition by extract(year from hire_date)) as year_cnt
from employees
group by extract(year from hire_date),
extract(month from hire_date)
) ym
) ym
where seqnum = 1
order by yyyy, mm;
嗯,你可以在没有这么多子查询的情况下做到这一点:
with ym as (
select extract(year from hire_date) as yyyy
extract(month from hire_date) as mm,
count(*) as cnt,
sum(count(*)) over (partition by extract(year from hire_date)) as yearcnt
from employees
group by extract(year from hire_date), extract(month from hire_date)
)
select *
from ym
where yearcnt = (select max(yearcnt) from ym)
order by yyyy, mm;
当然,如果两年具有相同的最大值,则会返回多年。
答案 1 :(得分:0)
使用PL / SQL我发现了这个:
declare
recuperation float;
CURSOR newRequest(recuperationDonnes float) is select count(employee_id) as nombreEmployes,
extract(month from hire_date) as mois from employees where
extract(year from hire_date) = (recuperationDonnes) group by extract(month from hire_date);
a float;
a1 float;
begin
select extract (year from hire_date) as annee into recuperation from employees having count
(employee_id) >= all (select count (employee_id) as emp from employees group by extract(year
from hire_date)) group by extract(year from hire_date);
OPEN newRequest(recuperation);
LOOP
FETCH newRequest into a,a1;
Exit when newRequest%NotFound;
dbms_output.put_Line('Year: '||recuperation||' mois: '||a1||' nombreEmployes: '||a);
END LOOP ;
CLOSE newRequest;
end;