我试图转动CTE的结果。由于隐私法,我无法在此处提供我的查询和结果集,但示例如下所示:
WITH CTE1
AS ( select ....)
,CTE2
AS (Select...)
,CTE3
as (Select...)
以下是我的CTE2的结果:
我希望结果为
我在这里遇到的主要问题是使用CTE2和CTE3之间的多个动态数据透视列来旋转结果集,因为我需要在CTE3中使用数据透视数据。有没有将CTE更改为TempTable的解决方案?任何帮助将不胜感激。
答案 0 :(得分:0)
我认为它会是这样的。
Dynamic Pivot:
DECLARE @query VARCHAR(4000)
DECLARE @years VARCHAR(2000)
SELECT @years = STUFF(( SELECT DISTINCT'],[' + [factor_label]
FROM [TEMP_lacp_factors]
ORDER BY '],[' + [factor_label]
FOR XML PATH('')
), 1, 2, '') + ']'
SET @query =
'SELECT * FROM
(
SELECT [date_],[issue_id],[cusip],[Factor_value],[factor_label]
FROM [TEMP_lacp_factors]
)t
PIVOT (MAX([factor_value]) FOR [factor_label]
IN ('+@years+')) AS pvt'
EXECUTE (@query)
Dynamic Pivot and Select Into:
-- Drop the table; you create it dynamically
Drop Table tempTable
--Start creating all objects for Dyanmic Pivot
DECLARE @query VARCHAR(4000)
DECLARE @years VARCHAR(2000)
SELECT @years = STUFF(( SELECT DISTINCT'],[' + [factor_label]
FROM [TEMP_lacp_factors]
ORDER BY '],[' + [factor_label]
FOR XML PATH('')
), 1, 2, '') + ']'
SET @query =
-- Objects that are created above, are put into the table you are about to create below
'SELECT * INTO tempTable FROM (SELECT * FROM
(
SELECT [date_],[issue_id],[cusip],[Factor_value],[factor_label]
FROM [TEMP_lacp_factors]
)t
PIVOT (MAX([factor_value]) FOR [factor_label]
IN ('+@years+')) AS pvt) X'
EXECUTE (@query)
-- Select everything from the dynamically created table ('tempTable') to see results
Select * from tempTable
我不能100%确定你在做什么,所以这只是一个最好的猜测。