Привет, вы можете использовать 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