Для динамического года pivoting
наш единственный вариант - использовать динамические запросы.
получение данных за последние 3 года
between dateadd(yy, -3, getdate()) and getdate()
полный запрос:
select * into #res from (
select '10/23/2018' as d ,'Leon' City, 1088 as price
union all
select '2/27/2018' ,'NewYork' ,1312
union all
select '4/19/2017' ,'Texas' ,1303
union all
select '4/19/2017' ,'Leon' ,1303
union all
select '4/19/2019' ,'London' ,1303
union all
select '4/19/2019' ,'NewYork' ,2000
union all
select '3/19/2019' ,'NewYork' ,1000
union all
select '3/19/2020' ,'NewYork' ,1000
union all
select '3/19/2020' ,'London' ,3000
union all
select '3/19/2020' ,'Texas' ,1000
)res
declare @cols nvarchar(max);
declare @sql nvarchar(max);
select @cols =
stuff((select N'],[Avg' + d
from (select distinct right(d, 4) as d
from #res where right(d, 4) between year(getdate())-1 and year(getdate())+1) AS t1
for xml path('')
), 1, 2, '') + N']';
set @sql = N'Select City, ' + @cols + N'
from (select City, concat(''Avg'', right(d, 4)) as d, price from #res)t1
pivot
(
avg(t1.price)
for t1.d in (' + @cols + N')
) p
'
print @sql;
exec sp_executesql @sql;
drop table #res