我有以下表格:
如何将上表转换为以下结构?我尝试使用数据透视表但无法使其工作。
答案 0 :(得分:1)
您需要查找SQL PIVOT。
代码:
SELECT *
FROM
(
SELECT Prodname,
pcode,
Biiledamt
FROM Product
) p
PIVOT
(
SUM (Biiledamt)
FOR Prodname IN ([Prod1],[Prod2],[Prod3],[Prod4])
) AS pvt
如果您事先不知道列,则可以check this fiddle动态生成要使用的列。
代码是:
DECLARE @cols AS VARCHAR(MAX),
@query AS VARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',[' + Prodname +']'
FROM Product c
FOR XML PATH(''), TYPE
).value('.', 'VARCHAR(MAX)')
,1,1,'')
SET @query =
' SELECT *
FROM
(
SELECT Prodname,
pcode,
Biiledamt
FROM Product
) p
PIVOT
(
SUM (Biiledamt)
FOR Prodname IN (' + @cols + ')
) AS pvt
'
EXEC(@query)