考虑一个表
employee id report_year report_quarter sequencenumber quarter1_wage quarter2_wage
101 2015 1 1 1000 0
101 2015 1 2 2000 0
102 2016 2 1 3000 0
102 2016 2 2 0 4000
查询的结果必须是
Total wages
6000
与2015年一样,最高序列号为2的员工ID 101在第1季度以下为2000,因为报告_quarter表示1需要添加取此值并添加到
2016年最高序号为2的员工ID 102有4000(quarter2_wage) 报告_quarter表示它是2
答案 0 :(得分:0)
我真的不明白为什么你要这样总结,但忽略你将会在各个方面聚合,从而得到名称" Total Wages"是错误的领导,这就是你如何实现这一目标。
--Assign a row number per employee based off the sequence number.
--This will assign 1 to the highest sequence number for each employee
with cte as(
select
*,
ROW_NUMBER() over (partition by [employee id] order by sequencenumber desc) as rn
from yourTable)
--Sum and add the two quarters for all employees where the row number = 1
--Which is the highest sequence
select
sum(quarter1_wage) + sum(quarter2_wage) as TotalWages
from cte
where rn = 1
答案 1 :(得分:0)
你有没有试过这样的事情:
WITH cte0 AS(
SELECT 101 AS employeeid,2015 AS report_year,1 AS report_quarter,1 AS sequencenumber,1000 AS quarter1_wage,0 AS quarter2_wage union all
SELECT 101 ,2015 ,1 ,2 ,2000 ,0 union all
SELECT 102 ,2016 ,2 ,1 ,3000 ,0 union all
SELECT 102 ,2016 ,2 ,2 ,0 ,4000
),
cte1 as(
SELECT employeeid,report_year,report_quarter,MAX(sequencenumber) AS maxseqnum
FROM cte0
GROUP BY employeeid,report_year,report_quarter)
SELECT SUM(quarter1_wage+quarter2_wage) AS [Total wages]
FROM cte0 c0
INNER JOIN cte1 c1
ON c0.report_year = c1.report_year AND c0.report_quarter = c1.report_quarter AND c0.employeeid = c1.employeeid AND c0.sequencenumber = c1.maxseqnum