我的数据格式如下表所示。我在Quantity(MG)的最后一列上应用了sum的聚合函数。
c.sort_by(&:last).map(&:first)
#=> ["{8}{51} lorem ipsum",
# "{98} Thx",
# "{108}{0.8}{907} aa",
# "{108}{0.8}{908} aa",
# "{109}{07} OK",
# "{109}{08} OK"]
我的选择SQL看起来像这样。
ITEM STORE Quantity(MG)
Rice Bags ABC 150
Sugar Bags ABC 200
Rice Bags NEW 50
Sugar Bags New 20
Rice Bags Alpha 25
我面临的问题是有一个声明我希望SQL比较给定项目的所有数量值的总和(比如米袋,150 + 50 +25 = 225)。但是通过上面的查询它没有按预期工作。当我应用条件“具有SUM(数量(MG)> 50”时,它实际上将值50与每个唯一行进行比较并跳过米袋数量小于50的行(在这种情况下是行#5)。理想情况下,不应该跳过这一行,因为米袋数量的总和是225,所以不应该跳过米袋的行。
通过设置应用此组的过滤器的解决方案是什么?
答案 0 :(得分:1)
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
答案 1 :(得分:0)
我认为这就是你想要的:
;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
答案 2 :(得分:0)
您需要在Quantity(MG)
上应用群组总和:
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