DB2 sql - 月度数据表

时间:2017-11-22 21:33:08

标签: sql db2

我有一张包含三个主键的月度数据表。考虑到这3个主键,它们以月为单位存储为一条记录。我想选择

  1. 当前月份数据的总和
  2. 当前季度数据的总和
  3. 当年数据总和
  4. Source Table 
    ===========  
    monthenddate key1 key2 key3 Data1  updated  
    11/30        1     2     3    50    11/1  
    10/30        1     2     3    50    10/1  
    1/31         1     2     3    50    1/1  
    
    target Table  
    ===========  
    key1 key2 key3 Month   Qtr    Yr    updated  
     1     2     3    50   100    150    11/1  
    

    有人可以帮忙吗

1 个答案:

答案 0 :(得分:0)

db2对于这个东西来说很简单,api就是你想要的名字:

select key1, key2, key3,
  sum(case when month(updated) = month(current date) then data1 else 0 end) as Month,
  sum(case when quarter(updated) = quarter(current date) then data1 else 0 end) as Qtr,
  sum(case when year(updated) = year(current date) then data1 else 0 end) as Yr,
  max(updated) as updated
from source_table
-- select just this year
where year(updated) = year(current date)
group by key1, key2, key3