考虑我们有这样一个表:
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 :(得分: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
答案 1 :(得分:0)
一种方法是使用窗口函数查找每年和每季度最大序列号的记录。
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