嵌套 Select 与 Pivot SQL 的 CTE

Nested Select vs CTE for Pivot SQL


具有 CTE


;with TERMS_DAYS AS 
(
    SELECT *
    ,replace(RIGHT(TERMS, LEN(terms) - 5), '-', '') AS DUE
    ,CASE WHEN replace(RIGHT(Terms, LEN(terms) - 5), '-', '') < 10  THEN 30 ELSE 
     CASE WHEN replace(RIGHT(Terms, LEN(terms) - 5), '-', '')  > 45  THEN replace(RIGHT(Terms, LEN(terms) - 5), '-', '') + 30 
     ELSE replace(RIGHT(Terms, LEN(terms) - 5), '-', '')  * 3 END 
        END                                         AS ELIGIBLE_T
    ,DATEDIFF(DD,"DATE",@p_DATE)                    AS t_DAYS
    FROM #t_BBC_LOAD
)
, ELIGIBLE AS 
(   
    SELECT *
            ,CASE WHEN 91 < t_DAYS THEN 'N' ELSE 'Y' END AS [CURRENT]
    FROM TERMS_DAYS
)
, FOREIGN_TOTALS AS 
(
    SELECT   CUSTOMER
            ,COUNTRY
            ,SUM(AMOUNT) AMOUNT
            ,[CURRENT]
            ,MS
    FROM ELIGIBLE
    GROUP BY CUSTOMER, COUNTRY, [CURRENT], MS
)
, TOTALS AS 
(
SELECT   CUSTOMER
        ,COUNTRY
        ,ISNULL(Y,0) Y
        ,ISNULL(N,0) N
        ,MS
FROM FOREIGN_TOTALS
)
select * from TOTALS
  PIVOT (SUM(AMOUNT) FOR [CURRENT] IN (Y, N)) AS P

没有 CTE


SELECT 
     Customer
    ,Country
    ,isnull(Y,0) as Y
    ,isnull(N,0) as N
    ,MS
FROM(
     SELECT CUSTOMER, COUNTRY, sum(AMOUNT) as AMOUNT, [CURRENT], MS
     FROM (
            SELECT *
            ,CASE WHEN 91 < t_DAYS THEN 'N' ELSE 'Y' END AS [CURRENT] --Eligble
            FROM(SELECT *
                ,replace(RIGHT(TERMS, LEN(terms) - 5), '-', '') AS DUE
                ,CASE WHEN replace(RIGHT(Terms, LEN(terms) - 5), '-', '') < 10  THEN 30 ELSE 
                 CASE WHEN replace(RIGHT(Terms, LEN(terms) - 5), '-', '')  > 45  THEN replace(RIGHT(Terms, LEN(terms) - 5), '-', '') + 30 
                 ELSE replace(RIGHT(Terms, LEN(terms) - 5), '-', '')  * 3 END 
                    END                                         AS ELIGIBLE
                ,DATEDIFF(DD,"DATE",@p_DATE)                    AS t_DAYS
                FROM #t_BBC_LOAD)
    EXP12G) ESGS

GROUP BY CUSTOMER, COUNTRY, [CURRENT], MS) as exp34
-----------------------------------------------------------------------------------------------------------------
PIVOT (SUM(AMOUNT) FOR [CURRENT] IN (Y, N)) AS P;
go

“没有 CTE”或“woCTE”运行没问题。我的任务是清理并重新分配原始查询中其他地方的一些值。但是,我 运行 遇到了麻烦。 woCTE 代码 运行s 并识别嵌套的“y”和“n”引用,即使它们不存在于最终 select 中。当我 运行(我认为)是等效的 CTE 时,它不会识别“y/n”引用。它如何在 selected 的情况下存储柱状数据?

我是 运行宁 2019 年,原始代码来自 2011 年,但同样,运行 开始修改时速度缓慢但完整。

select * 已删除,不再使用。枢轴需要枢轴函数中使用的特定字段。我的错。