Для обработки переменного количества столбцов (недель) вы можете использовать динамический TSQL:
create table #tmp(location varchar(50), Week varchar(6),Expenses int)
insert into #tmp values
('Backoffice' ,'201851', 80),('frontoffice','201852',110),('Backoffice' ,'201901',120),('Backoffice' ,'201902', 70),('frontoffice','201903', 68)
declare @startDate date = '20190131' --Start date, probably you'll want to put Getdate() here
declare @weeks table ([weekNumber] nvarchar(4), [weekYear] nvarchar(4))
declare @weekCount int = 10 --numbers of weeks to show
declare @counter int = 0 --counter to loop on all weeks
declare @weekList varchar(max)='' --holds the list of dynamically generated column headers
declare @sql varchar(max)='' --holds the complete dynamical TSQL query
set @counter = @weekCount
while @counter > 0
begin
insert into @weeks
SELECT right('0' + cast(DATEPART(wk, DATEADD(WK,-(@counter),@startDate)) as varchar(2)),2)
, DATEPART(year, DATEADD(WK,-(@counter),@startDate))
set @counter = @counter - 1
end
select @weekList = @weekList + '[' + [weekYear] + [weekNumber] + '],' from @weeks
set @weekList = SUBSTRING(@weekList, 1, len(@weekList) - 1)
set @sql = @sql + ' SELECT * from'
set @sql = @sql + ' (SELECT[week]'
set @sql = @sql + ' ,[Expenses]'
set @sql = @sql + ' from #tmp where location = ''Backoffice'''
set @sql = @sql + ' ) as Total_Expenses pivot (sum([expenses]) for [week] in ('+@weekList+')) as pivotable;'
--execute dynamic query
exec(@sql)
Вывод с @weekCount = 5
:
Вывод с @weekCount = 10
: