gpt4 book ai didi

sql-server - 透视到 SQL Server

转载 作者:行者123 更新时间:2023-12-03 10:07:03 25 4
gpt4 key购买 nike

我有一个包含列的表格:

Anno, Description, Number
________________________
2011 Example1 12
2013 Example2 9
2011 Example4 8

……

Description 列中的值是动态的

我必须生成如下表格:

Anno Example1 Example2 Example3 Example4 ........
--------------------------------------------------
2011 12 0 0 8 ........
2012 0 23 24 36 ........
......

我创建了这样一个 View :

Declare @cols AS NVARCHAR(Max),
@query AS NVARCHAR(Max)

Select @cols = STUFF(( Select ','+QUOTENAME(Description)
FROM mytable
GROUP BY Description
Order by Description
FOR XML PATH ('',TYPE
).value('.','NVARCHAR(Max)'),1,1,'')

SET @query= 'Select Anno, '+cols+' from
(Select Anno, Description, Number
FROM mytable ) as x
PIVOT
(
SUM(Number)
FOR Description in ('+cols+')
) pvt'

EXECUTE(@query)

它返回一个错误:

Incorrect syntax near ','

最佳答案

试试这个 -

DECLARE @query NVARCHAR(MAX)

SELECT @query = '
SELECT Anno, ' + cols + '
FROM (
SELECT Anno, Description, Number
FROM dbo.mytable
) x
PIVOT
(
SUM(Number) FOR [Description] IN (' + cols + ')
) pvt'
FROM (
SELECT cols = STUFF((
SELECT ', [' + [Description] + ']'
FROM dbo.mytable d
GROUP BY [Description]
ORDER BY [Description]
FOR XML PATH (''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
) t

EXEC sys.sp_executesql @query

关于sql-server - 透视到 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16840290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com