我有一台台式机。数据如下所示
Item Sub_Item qty
XYZ ABC 100
XYZ ABC 80
XYZ PQR 120
DEF KKK 100
DEF KKK 50
DEF LLL 120
DEF LLL 70
QQQ DDD 200
PQR OOO 100
PQR OOO 60
情节是,我只需要那些记录, Item中有两个或多个不同的sub_items, 和查询应返回sub_item的总和(qty)的最小值 如果按项目&组分组,它应该更新。 sub_item只返回一行。
上表的查询结果如下:
Item Sub_Item qty
XYZ PQR 120
DEF KKK 150
它应该更新其他记录,因为它们不符合标准。 请帮我查询。
答案 0 :(得分:1)
select
y.Item,
y.SubItem,
y.GroupQty
from
( -- Rank the items by quantity and exclude the items that only have 1 subitem.
select
x.Item,
x.SubItem,
x.GroupQty,
dense_rank() over (partition by x.Item order by x.GroupQty) as GroupRank
from
( -- Group by item and subitem. Sum quantity and count the number of subitems per item.
select
t.Item,
t.Sub_Item,
sum(t.qty) as GroupQty,
count(distinct t.sub_item) over (partition by t.Item) as SubItemCount
from
YourTable t
group by
t.item,
t.sub_item ) x
where
x.SubItemCount > 1) y
where
y.GroupRank = 1 -- Return only the subitems with the lowest sum.