Running Multiplication in T-SQL

后端 未结 6 1158
無奈伤痛
無奈伤痛 2021-02-03 13:16

GTS Table

CCP months   QUART   YEARS  GTS
----  ------  -----    ----- ---
CCP1    1       1   2015    5
CCP1    2       1   2015    6
CCP1    3       1   2015         


        
6条回答
  •  -上瘾入骨i
    2021-02-03 13:47

    Another alternative is using stacked/cascaded CTEs:

    ;WITH CteFirstQtr AS(
        SELECT g.*, 
            result = b.BASELINE * g.GTS
        FROM gts g
        INNER JOIN BASELINE b
            ON b.CCP = g.CCP
            AND b.YEARS = g.YEARS
            AND b.QUART = g.QUART
    ),
    CteSecondQtr AS(
        SELECT g.*,
            result = t.result * g.gts
        FROM gts g
        CROSS APPLY(
            SELECT SUM(result)
            FROM CteFirstQtr
            WHERE
                CCP = g.CCP
                AND Years = g.Years
                AND QUART = 1
        )t(result)
        WHERE g.QUART = 2
    ),
    CteThirdQtr AS(
        SELECT g.*,
            result = t.result * g.gts
        FROM gts g
        CROSS APPLY(
            SELECT SUM(result)
            FROM CteSecondQtr
            WHERE
                CCP = g.CCP
                AND Years = g.Years
                AND QUART = 2
        )t(result)
        WHERE g.QUART = 3
    ),
    CteFourthQtr AS(
        SELECT g.*,
            result = t.result * g.gts
        FROM gts g
        CROSS APPLY(
            SELECT SUM(result)
            FROM CteThirdQtr
            WHERE
                CCP = g.CCP
                AND Years = g.Years
                AND QUART = 3
        )t(result)
        WHERE g.QUART = 4
    )
    SELECT *  FROM CteFirstQtr UNION ALL
    SELECT *  FROM CteSecondQtr UNION ALL
    SELECT *  FROM CteThirdQtr UNION ALL
    SELECT *  FROM CteFourthQtr
    

提交回复
热议问题