我试图创建一个带有PERIOD列作为标题的动态数据透视表 - 这段时间实际上是与月份连接的年份,例如201608
这个一直在绊倒,我尝试了很多我在网上找到的解决方案,并试图完全重新排列几次。
任何人都可以帮助我吗?查询本身非常简单。
DECLARE @query VARCHAR
DECLARE @PERIOD VARCHAR = '201608'
DECLARE @col1 AS VARCHAR
SELECT @col1 = ISNULL(@col1, 0) FROM (SELECT DISTINCT [PERIOD] AS col1
FROM [DimDate] WHERE LEFT([PERIOD], 4) = LEFT(@PERIOD, 4)) AS [TEST]
SET @query =
'SELECT *
FROM
(SELECT 1 as NGroup, [PERIOD], MEMBERSHIP_LEVEL, Amount
from [NewMember]) AS s
PIVOT
(COUNT(Amount) FOR [PERIOD] IN (' + @col1 + ')) AS pvt'
PRINT @query
EXEC @query