首先我不知道这算Oracle的基础还是Oracle板块的高级,所以,我那边也会有个同名的帖子。其次,本问题使用Oracle的hr用户,这样方便大家测试,如果你的hr登录不进,可以尝试文末的代码,文末哦。先看这个句子:-- 按月统计每个月雇佣的人数
select to_char(hire_date, 'yyyy-mm') "TIME"
     , count(employee_id) "COUNT"
from employees
group by to_char(hire_date, 'yyyy-mm')
order by "TIME";部分结果便是这样的:
注意,不仅月份不全,而且年份也不全,我使用LAG("TIME", 12, 0)做比较肯定不能得到同期的数据,请问我该怎么写SQL?一个办法是:我手工补全月份和年份,让对应的COUNT为0,但是这样工作量有些大了。
-- 分析函数做同期比较
select "TIME", "COUNT"
     , lag("COUNT", 12, 0) over (order by "TIME") as "去年同期"
from 
        (select to_char(hire_date, 'yyyy-mm') "TIME"
             , count(employee_id) "COUNT"
        from employees
        group by to_char(hire_date, 'yyyy-mm')) 
;-- 使用hr用户
conn system@orcl
alter user hr identified by hr;
alter user hr account unlock;
conn hr/hr@orcl;

解决方案 »

  1.   


    ----试试 
    select to_char(a.hire_date, 'yyyy-mm') "TIME"
         , count(a.employee_id) "COUNT",
    nvl((select count(*) from employees b where to_char(add_months(a.hire_date,-12), 'yyyy-mm')=to_char(b.hire_date, 'yyyy-mm')),0)
    from employees a
    group by to_char(a.hire_date, 'yyyy-mm')
    order by "TIME";
      

  2.   


    提示如下错误,GROUP BY语句不完整?ORA-00979: not a GROUP BY expression
    00979. 00000 -  "not a GROUP BY expression"
    *Cause:    
    *Action:
    Error at Line: 29 Column: 65
    我把NVL那条表达式加到GROUP BY中,提示:ORA-22818: subquery expressions not allowed here
    22818. 00000 -  "subquery expressions not allowed here"
    *Cause:    An attempt was made to use a subquery expression where these
               are not supported.
    *Action:   Rewrite the statement without the subquery expression.
    Error at Line: 31 Column: 19
      

  3.   

    with tb as
    (select trunc(hire_date) dt,count(employee_id) counts
    from employees 
    group by trunc(hire_date))
    select a.dt,a.counts,(select nvl(b.counts,0) from tb b where add_months(a.dt,-12)=b.dt) 同期的
    from tb a
      

  4.   

    --还有什么问题with tb as
    (select trunc(hire_date) dt,count(employee_id) counts
    from employees 
    group by trunc(hire_date))
    select to_char(a.dt,'yyyy-mm') times,a.counts,(select nvl(b.counts,0) from tb b where add_months(a.dt,-12)=b.dt) 同期的
    from tb a