gpt4 book ai didi

sql - 寻找只购买没有其他人购买的商品的客户

转载 作者:行者123 更新时间:2023-11-29 11:58:53 25 4
gpt4 key购买 nike

下面是订单列表,有没有办法找到客户的person_id购买了没有其他人购买的产品?

CREATE TABLE orders
AS
SELECT product_id, person_id
FROM ( VALUES
( 1 , 1 ),
( 2 , 1 ),
( 2 , 2 ),
( 3 , 3 ),
( 12, 6 ),
( 10, 3 )
) AS t(product_id, person_id);

结果如下表:

| person_id |
|-----------|
| 3 |
| 6 |

我是否必须找出所有购买过无人购买的商品的人,然后创建一个不包括这些人的表格?

最佳答案

您希望此人购买的所有产品都是独一无二的。

select person_id
from (select t.*,
min(person_id) over (partition by product_id) as minp,
max(person_id) over (partition by product_id) as maxp
from t
) t
group by person_id
having sum(case when minp <> maxp then 1 else 0 end) = 0;

您可能在想“嗯?这是做什么用的?”。

子查询计算每个产品的最小人数和最大人数。如果这些相同,那么这个人就是唯一的购买者。

然后 having 检查给定的人没有非单一购买者的产品。

也许更直观的逻辑表述是:

select person_id
from (select t.*,
count(distinct person_id) over (partition by product_id) as numpersons
from t
) t
group by person_id
having max(numperson) = 1;

唉,Postgres 不支持 COUNT(DISTINCT) 作为窗口函数。

关于sql - 寻找只购买没有其他人购买的商品的客户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43417515/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com