我写了一个查询来生成数据透视。该代码运行得很好。 代替对值(“ 1”,“ 2”,“ 3”)进行硬编码,是否可以编写子查询?
SELECT *
FROM (
SELECT * from #Registered2
) as s
PIVOT
(
SUM(s.Registered_customer_Count)
FOR [Offer_cover_id] IN ("1","2","3")
)AS pvt
答案 0 :(得分:0)
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX);
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.[Offer_cover_id])
FROM #Registered2 c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT ' + @cols + ' from
(
select*
from Registered2
) x
pivot
(
SUM(Registered_customer_Count)
for [Offer_cover_id] in (' + @cols + ')
) p '
execute(@query)