考虑一个表
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)
SELECT SUM(quarter1_wage )+SUM(quarter2_wage) AS total
,MAX(sequencenumber)
,report_year
FROM table
GROUP BY report_year
答案 1 :(得分:0)
与Ties和Order by一起使用,只获得EmployeeId的最高序列号,然后得到派生表的总和
Select SUM(quarter1_wage )+SUM(quarter2_wage) AS total from (
Select Top 1 with Ties * from table
ORDER BY row_number() over (partition by employee_id order by sequencenumber desc)) as DerivedTable