2016-12-15 88 views
1

考虑,我们有这样的表总额:取基于最高序列号每每季度每每年

eid report_year report_qurter seqnum quarter1_grossamt quarter2_grossamt 
101 2015  1    0  20000.00   0.00 
101 2015  1    1  3000    0.00 
102 2016  1    0  40000    0.00 
102 2016  1    2  6000    0.00 
101 2015  2    0  0.00    20000 

输出应该是:

eid report_year report_quarter   seqnum   grossamt 
101 2015   1      1    3000 
102 2016   1      2    6000    
101 2015   2      0    20000   

记录应依据打印每个季度的最大seqnum和相关的总金额应打印

回答

0

一种方法是使用窗口函数来查找每个y具有最大序号的记录耳朵和季度。

SELECT t.eid, 
     t.report_year, 
     t.report_quarter, 
     t.seqnum, 
     t.grossamt 
FROM 
(
    SELECT eid, 
      report_year, 
      report_quarter, 
      seqnum, 
      MAX(seqnum) OVER(PARTITION BY report_year, report_quarter) maxSeqNum, 
      CASE WHEN report_quarter = 1 
       THEN quarter1_grossamt 
       ELSE quarter2_grossamt END AS grossamt 
    FROM yourTable 
) t 
WHERE t.seqnum = t.maxSeqNum 
1
SELECT eid , T.report_year , T.report_qurter , T.seqnum , CASE WHEN 
quarter1_grossamt <> 0 THEN quarter1_grossamt ELSE quarter2_grossamt END 
FROM #Table T 
JOIN 
(
    SELECT report_year,report_qurter,MAX(seqnum) seqnum 
    FROM #Table 
    GROUP BY report_year,report_qurter 
)A ON A.report_year = T.report_year AND T.report_qurter = A.report_qurter  
AND T.seqnum = A.seqnum