Достигать тех же результатов без общего табличного выражения - PullRequest
0 голосов
/ 27 июня 2019

Мой SQL-код выдает per_month, per_month min, per_month max и per_month стандартное отклонение.Но я сделал это с 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 голосов
/ 27 июня 2019

вы можете использовать subquery без cte

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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...