示例:
表:
+---+----+----+----+
| id|year| A | B |
+---+----+----+----+
|101|2017| 50 | 40 |
|102|2017| 40 | 45 |
|103|2017| 80 | 15 |
|104|2017| 0 | 0 |
|101|2018| 65 | 75 |
|102|2018| 50 | 40 |
|103|2018| 25 | 55 |
|104|2018| 0 | 0 |
+---+----+----+----+
*下一年的数据等将添加到表格中
因此,根据上表,我希望得到如下结果:
+---+--------------+--------------+-------------+
| id|Total for 2017|Total for 2018|Overall Total|
+---+--------------+--------------+-------------+
|101| 90 | 140 | 230 |
|102| 85 | 90 | 175 |
|103| 95 | 80 | 175 |
+---+--------------+--------------+-------------+
仅显示整体总数不为零的ID。
是否有查询我可以获得上述结果?
答案 0 :(得分:4)
select id,
sum(case when year = 2017 then a+b else 0 end) as [2017],
sum(case when year = 2018 then a+b else 0 end) as [2018],
sum(a+b) as Total
from your_table
group by id
having sum(a+b) > 0
答案 1 :(得分:1)
最简单的方法是使用conditional aggregation
:
SELECT id
,SUM(CASE WHEN year=2017 THEN A+B ELSE 0 END) AS Total_for_2017
,SUM(CASE WHEN year=2018 THEN A+B ELSE 0 END) AS Total_for_2018
,SUM(A+B) AS Overall_Total
FROM tab
GROUP BY id;
如果A或B可以为空,那么你应该用ISNULL
包裹它。
答案 2 :(得分:0)
您好,您可以使用pivot来处理更多动态数据。请参阅下面的示例,了解固定年份和动态年份。试试一次。
CREATE TABLE #yt
( [id] int, [year] int, [a] int,[b] int);
INSERT INTO #yt
VALUES(101,2017,50,40),(102,2017,40,45),(103,2017,80,15)
,(104,2017,0,0),(101,2018,65,75),(102,2018,50,40)
,(103,2018,25,55),(104,2018,0,0)
select *,[2017]+[2018] total from
(select [id],[year],[a]+[b] as [total] from #yt)
a1
pivot
(sum([total])
for [year] in ([2017],[2018])
) piv
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
set @cols = stuff((select ',' + QUOTENAME([year] ) from #yt group by
[year] order by [year] for xml path('')),1,1,'')
set @query = ' select *,'+ replace(@cols,',','+') +' total from
(select [id],[year],[a]+[b] as [total] from #yt)
a1
pivot
(sum([total]) for [year] in ('+@cols+')) piv'
EXECUTE sp_executesql @query
drop table #yt