如何根据不同的分组条件得到两个数量列的总和?
Posted
技术标签:
【中文标题】如何根据不同的分组条件得到两个数量列的总和?【英文标题】:How to get sum of two quantity columns based on different grouping conditions? 【发布时间】:2019-11-13 16:21:42 【问题描述】:从 table1 和 table2 的内部连接,交货时加入,我想根据分组工厂、零件和 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】:您可以使用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];
【讨论】:
我收到错误 PLANT 在选择列表中无效,因为它既不包含在聚合函数或 GROUP BY 子句中。 DECLARE @REPORT AS NVARCHAR(50)='2019-06-19 00:00:00.000' SELECT *, SUM(CASE WHEN (P_DATE DATEADD(DAY,-7 ,@REPORT)) THEN QTY_PICKED ELSE 0 END) OVER(PARTITION by Plant,Parts,P_DATE)AS SHIPPED, SUM(CASE WHEN E_DATE>@REPORT AND E_DATE @REPORT AND E_DATE 您需要为每个聚合函数应用OVER
子句。以上是关于如何根据不同的分组条件得到两个数量列的总和?的主要内容,如果未能解决你的问题,请参考以下文章