在没有公用表表达式的情况下达到相同的结果

时间:2019-06-27 02:22:17

标签: sql sql-server tsql

我的SQL代码产生每月,每月最小,每月最大和每月标准偏差。但是我已经通过CTE完成了。现在我想不用CTE。

;WITH QTY_T AS(
SELECT 
            YEAR(SHIP_DATE) [Year], 
            MONTH(SHIP_DATE) [Month], 
            T1.PLANT AS PLANTS,
            WC AS W_C,
            T2.SHIP_TO AS SHIP_TO,
            T1.PARTS AS PARTS,
            SUM([QTY_MII]) AS [QTY_MONTH]
    FROM TABLE1 T1
            INNER JOIN 
                TABLE2 T2
                ON
                T2.OBD = T1.OBD
            INNER JOIN
                TABLE3 T3
                ON T1.OBD=T3.OBD AND T1.ITEM = T3.ITEM AND T1.PLANT =  T3.PLANT
            INNER JOIN
                TABLE4 T4
                ON T3.SHIP_LBL = T4.HU_CODE AND T4.STATUS ='SHIPPED'AND T4.PLANT = T3.PLANT
    GROUP BY 
                T1.PLANT,WC,SHIP_TO,T1.PARTS,YEAR(SHIP_DATE),MONTH(SHIP_DATE)
) SELECT  
        PLANTS,W_C,PARTS,SHIP_TO,
        ROUND(AVG(QTY_MONTH),3) AS QTY_SHIPPED_PER_MONTH,
        ROUND(MIN(QTY_MONTH),3) AS QTY_SHIPPED_PER_MONTH_MIN,
        ROUND(MAX(QTY_MONTH),3) AS QTY_SHIPPED_PER_MONTH_MAX,
        ROUND(AVG(QTY_MONTH),3) AS QTY_SHIPPED_PER_MONTH_AVG,
        ROUND(STDEV(QTY_MONTH),3) AS QTY_SHIPPED_PER_MONTH_STD
   FROM QTY_T
   GROUP BY PLANTS,W_C,QTY_T.SHIP_TO,QTY_T.PARTS

1 个答案:

答案 0 :(得分:0)

您可以在没有cte的情况下使用subquery

SELECT  
    PLANTS,W_C,PARTS,SHIP_TO,
    ROUND(AVG(QTY_MONTH),3) AS QTY_SHIPPED_PER_MONTH,
    ROUND(MIN(QTY_MONTH),3) AS QTY_SHIPPED_PER_MONTH_MIN,
    ROUND(MAX(QTY_MONTH),3) AS QTY_SHIPPED_PER_MONTH_MAX,
    ROUND(AVG(QTY_MONTH),3) AS QTY_SHIPPED_PER_MONTH_AVG,
    ROUND(STDEV(QTY_MONTH),3) AS QTY_SHIPPED_PER_MONTH_STD
FROM (
    SELECT 
        YEAR(SHIP_DATE) [Year], 
        MONTH(SHIP_DATE) [Month], 
        T1.PLANT AS PLANTS,
        WC AS W_C,
        T2.SHIP_TO AS SHIP_TO,
        T1.PARTS AS PARTS,
        SUM([QTY_MII]) AS [QTY_MONTH]
    FROM TABLE1 T1
        INNER JOIN TABLE2 T2 ON T2.OBD = T1.OBD
        INNER JOINTABLE3 T3 ON T1.OBD=T3.OBD AND T1.ITEM = T3.ITEM AND T1.PLANT =  T3.PLANT
        INNER JOIN TABLE4 T4 ON T3.SHIP_LBL = T4.HU_CODE AND T4.STATUS ='SHIPPED'AND T4.PLANT = T3.PLANT
    GROUP BY 
        PLANT,WC,SHIP_TO,T1.PARTS,YEAR(SHIP_DATE),MONTH(SHIP_DATE)
) as QTY_T
GROUP BY PLANTS,W_C,QTY_T.SHIP_TO,QTY_T.PARTS