如何根据不同的分组条件获取两个数量列的总和?

时间:2019-07-03 02:51:00

标签: sql sql-server tsql aggregate-functions

Table1 Table2

从表1和表2的内部联接中,在交货时联接,我想根据分组工厂,零件和exp_ship_date获得qty_to_ship的总和,以及根据分组工厂,零件和book_date分组得到qty_shipped的总和。这个想法是根据book_date计算发货数量,并根据exp_ship_date计算发货数量。

我尝试使用子查询,但无法获得正确答案

我尝试了什么

DECLARE @REPORT AS NVARCHAR(50)='2019-06-19 00:00:00.000'
SELECT
    PLANT,
    PARTS,
    YEAR(P_DATE) AS P_DATE,MONTH(P_DATE) AS P_DATE,DAY(P_DATE) AS P_DATE,
    ES_DATE AS ES_DATE,
    SUM(CASE WHEN (P_DATE<@REPORT AND P_DATE > DATEADD(DAY,-7,@REPORT)) THEN QTY_PICKED ELSE 0 END) AS SHIPPED,
    SUM(CASE WHEN ES_DATE>@REPORT AND ES_DATE < DATEADD(DAY,7,@REPORT) THEN QTY_MII ELSE 0 END) -SUM(CASE WHEN ES_DATE>@REPORT AND ES_DATE < DATEADD(DAY,7,@REPORT) THEN QTY_PICKED ELSE 0 END)  AS TO_SHIP
      FROM TABLE1 T1
      INNER JOIN
      TABLE2 T2 
      ON
      T1.DELIVERY = T2.DELIVERY

WHERE PLANT = 'XXX'
GROUP BY
    GROUPING SETS (
        (PLANT, PARTS,YEAR(P_DATE),MONTH(P_DATE),DAY(P_DATE)),
        (PLANT, PARTS,ES_DATE)
    )
ORDER BY
PLANT,
PARTS

1 个答案:

答案 0 :(得分:0)

您可以使用OVER子句根据每一行的不同分组来计算聚合:

SELECT *
     ,SUM(qty_to_ship) OVER (PARTITION BY plant, parts, exp_ship_date)
     ,SUM(qty_shipped) OVER (PARTITION BY plant, parts, book_date)
FROM table1 A
INNER JOIN table2 B
    ON A.[Delivery] = B.[Delivery];

然后保留所需的列,并使用DISTINCT删除重复的行。例如:

SELECT DISTINCT A.develiery
               ,A.plant
               ,A.parts
               ,SUM(qty_to_ship) OVER (PARTITION BY plant, parts, exp_ship_date)
               ,SUM(qty_shipped) OVER (PARTITION BY plant, parts, book_date)
FROM table1 A
INNER JOIN table2 B
    ON A.[Delivery] = B.[Delivery];