慕丝7291255
如果您使用的是SQL Server 2005+,则可以使用该PIVOT函数将数据从行转换为列。听起来你需要使用动态sql如果周未知,但最初使用硬编码版本更容易看到正确的代码。首先,这里有一些快速表定义和使用数据:CREATE TABLE #yt
(
[Store] int,
[Week] int,
[xCount] int);INSERT INTO #yt(
[Store],
[Week], [xCount])VALUES
(102, 1, 96),
(101, 1, 138),
(105, 1, 37),
(109, 1, 59),
(101, 2, 282),
(102, 2, 212),
(105, 2, 78),
(109, 2, 97),
(105, 3, 60),
(102, 3, 123),
(101, 3, 220),
(109, 3, 87);如果您的值已知,那么您将对查询进行硬编码:select *from (
select store, week, xCount from yt) srcpivot(
sum(xcount)
for week in ([1], [2], [3])) piv;请参阅SQL Demo然后,如果您需要动态生成周数,您的代码将是:DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)select @cols = STUFF((SELECT ',' + QUOTENAME(Week)
from yt group by Week order by Week
FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)')
,1,1,'')set @query = 'SELECT store,' + @cols + ' from
(
select store, week, xCount
from yt
) x
pivot
(
sum(xCount)
for week in (' + @cols + ')
) p 'execute(@query);请参阅SQL Demo。动态版本,生成week应转换为列的数字列表。两者都给出相同的结果:| STORE | 1 | 2 | 3 |---------------------------| 101 | 138 | 282 | 220 || 102 | 96 | 212 | 123 || 105 | 37 | 78 | 60 || 109 | 59 | 97 | 87 |