假设我们有一个如下所示的数据框:
order_id product seller
1 apple a
1 grape a
2 orange a
2 strawberry b
2 apple b
3 apple b
4 kiwi a
4 orange a
5 grape c
我的目标是首先按其
order_id
对它们进行分组,同时保留所有这些产品由唯一的 seller
交付的订单。因此,我希望得到的输出如下所示:
order_id product seller
1 apple a
1 grape a
3 apple b
4 kiwi a
4 orange a
5 grape c
有没有简单的方法可以实现?
这是一种使用 CTE 来确定每个订单关联多少个卖家的方法,然后将订单限制为只有一个卖家。
with seller_count as (
select order_id, count(distinct seller) as sellers
from orders
group by order_id
)
select o.*
from orders o
join seller_count sc
on o.order_id = sc.order_id
where sc.sellers = 1