比较 SQL 服务器中 "Group by subtotals" 的总计

Compare Grand total of "Group by subtotals" in SQL Server

我有以下形式的数据table。我在 Quantity(MG) 的最后一列应用了总和的聚合函数。

ITEM         STORE     Quantity(MG) 

Rice Bags     ABC      150 
Sugar Bags    ABC      200
Rice Bags     NEW      50 
Sugar Bags    New      20 
Rice Bags     Alpha    25 

我的 Select SQL 看起来像这样。

Select ITEM, STORE, SUM(Quantity(MG)
From....
.........
.........
Group by ITEM, STORE 
Having SUM(Quantity(MG) > 50 

我面临的问题是 having 语句,我希望 SQL 比较给定项目的所有数量值的总和(比如 Rice Bags,即 150 + 50 +25 = 225)。但是对于上面的查询,它没有按预期工作。当我应用条件 "Having SUM(Quantity(MG) > 50" 时,它实际上将值 50 与每个唯一行进行比较,并跳过米袋数量小于 50 的行(在本例中为第 5 行)。理想情况下不应跳过此行因为大米袋的总数量是 225,所以不应跳过大米袋的行。

通过设置对这个组应用这样的过滤器的解决方案是什么?

sum() over(partition by) 将为您完成这项工作:

Select ITEM, STORE, SUM(Quantity(MG)) over(partition by item,store) as sm
From table
where Quantity(MG)< 50

已编辑:

select ITEM, STORE,Quantity(MG),grp_sum from 
     (Select ITEM, STORE,Quantity(MG), SUM(Quantity(MG)) over(partition by item,store) as grp_sum
        From table)temp
        where grp_sum< 50

我想这就是你想要的:

;with cte as(select item, store, quantity, sum(quantity) over(partition by item) as groupedQuantity)
select item, store, sum(quantity) as quantity
from cte
where groupedQuantity > 50
group by item, store

您需要在 Quantity(MG):

上应用 Group Sum
select ITEM, STORE, sumQuantity
from
 (
   Select ITEM, STORE, SUM(Quantity) as sumQuantity
      ,SUM(SUM(quantity)) OVER (PARTITION BY ITEM) as groupSum 
   From....
   .........
   .........
   Group by ITEM, STORE
 ) as dt
where groupSum > 50