gpt4 book ai didi

sql - 具有 CTE 的动态枢轴

转载 作者:行者123 更新时间:2023-12-02 09:34:44 26 4
gpt4 key购买 nike

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

"Common table expression defined but not used."

如何基于 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)

最佳答案

以下是您可以如何做到的。我已经在查询中编写了逻辑

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

关于sql - 具有 CTE 的动态枢轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28270473/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com