日期之间的聚合

时间:2014-10-22 16:08:49

标签: sql oracle aggregation

我有以下问题,我试图计算一年中的工资总额。

select sum(case when date_key between to_char(sysdate,'yyyymm')
                                  and to_char(add_months(sysdate,-12), 'yyyymm')
                then salary end) as annual_salary 
from employee
group by emp_key

当我执行查询时,我在结果集中得到空值。

我实际上在员工表中有工资的有效数字。 我哪里错了?

3 个答案:

答案 0 :(得分:2)

只需反转2个边界,它们的顺序不正确:

...
between to_char(add_months(sysdate,-12), 'yyyymm')
   and to_char(sysdate,'yyyymm')

答案 1 :(得分:0)

select 
sum(case when date_key between to_char(sysdate,'yyyymm') and to_char(add_months(sysdate,-12),'yyyymm') then salary else 0 end) as annual_salary 
from employee group by emp_key

当expr1 ELSE expr2结束时的情况 如果你没有" ELSE expr2" Oracle认为它是空的

答案 2 :(得分:0)

select sum(case when date_key between 
                                   to_char(add_months(sysdate,-12), 'yyyymm') and to_char(sysdate,'yyyymm')
                then salary end) as annual_salary 
from employee
group by emp_key