具有CTE的动态枢轴

时间:2015-02-02 02:48:15

标签: sql sql-server tsql

我试图创建一个Common Table Express(CTE)来存储我需要的一些需要一堆内连接的数据。然后,我想使用动态透视列来旋转结果。我在下面写了查询但是我收到了错误

  

“已定义公用表表达式但未使用。”

如何在CTE上创建透视查询?顺便说一句,我可以在没有CTE的情况下完成,但我想知道我是否可以用CTE来做。

 DECLARE @cols nvarchar(max)
 DECLARE @sql nvarchar(max)
 SELECT @cols = isnull(@cols + ', ', '') + '[' +       Convert(varchar(max),T.CostCenterNumber) + ']' FROM (SELECT distinct   CostCenterNumber FROM CostCenters) as T
 ;With PivotData as (
 SELECT B.[Year], C.CostCenterNumber, C.CostCenterName, E.[Description] as     GLClass, D.Code, D.[GLDescription], A.Total
From GeneralLedgers A inner join
Years B on A.YearID = B.ID
inner join CostCenters C on
A.CostCenterID = C.ID
inner join GLCodes D on
A.GLCodeID = D.ID inner join
GLClassificationTypes E on 
D.GLClassificationTypeID = E.ID)


SELECT @sql = '
Select *
From(
SELECT [Year], CostCenterNumber, GLClass, Code, GLDescription, Total
FROM PivotData) as T
PIVOT 
    (
        Max(Total)
        for [CostCenterNumber] in (' + @cols + ')
    )) as P'
EXEC(@sql)

1 个答案:

答案 0 :(得分:5)

以下是如何做到这一点。我在查询中编写了逻辑

DECLARE
@cols nvarchar(max),
@stmt nvarchar(max)
SELECT @cols = isnull(@cols + ', ', '') + '[' + Convert(nvarchar(max),T.CostCenterNumber)+ ']' 
               FROM (SELECT distinct CostCenterNumber FROM CostCenters) as T

SELECT @stmt = '
-- Your CTE goes here
;WITH CTE AS
(
      SELECT [Year], E.[Description] as GLClass, Code, 
      GLDescription,  CostCenterNumber, Total
      FROM GeneralLedgers A inner join
      Years B on A.YearID = B.ID inner join
      GLCodes C on A.GLCodeID = C.ID inner join
      CostCenters D on A.CostCenterID = D.ID inner join
      GLClassificationTypes E on C.GLClassificationTypeID = E.ID
)
-- Pivoted reuslt
SELECT * FROM
(  
     -- Here you select the data from CTE
     SELECT * 
     FROM CTE
)as T
PIVOT 
(
     max(T.Total)
     for T.[CostCenterNumber] in (' + @cols + ')
) as P'
exec sp_executesql  @stmt = @stmt