If you are using SQL Server 2014+, then you can use the PIVOT
function to transform the data from rows into columns.
It sounds like you will need to use dynamic sql if the weeks are unknown but it is easier to see the correct code using a hard-coded version initially.
If your values are known, then you will hard-code the query:
1234567891011121314 Store Week xCount------- ---- ------102 1 96101 1 138105 1 37109 1 59101 2 282102 2 212105 2 78109 2 97105 3 60102 3 123101 3 220109 3 87
you would like it to come out as a pivot table, like this:
123456 Store 1 2 3 4 5 6....-----101 138 282 220102 96 212 123105 37109
You need the next code:
1234567891011 select *from(select store, week, xCountfrom yt) srcpivot(sum(xcount)for week in ([1], [2], [3])) piv;
Then if you need to generate the week number dynamically, your code will be:
1234567891011121314151617181920212223 DECLARE @cols AS NVARCHAR(MAX),@query AS NVARCHAR(MAX)select @cols = STUFF((SELECT ',' + QUOTENAME(Week)from ytgroup by Weekorder by WeekFOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),1,1,'')set @query = 'SELECT store,' + @cols + ' from(select store, week, xCountfrom yt) xpivot(sum(xCount)for week in (' + @cols + ')) p 'execute(@query);