2016-12-15 66 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