[英]MySQL: Get number of users who bought product b AFTER they bought product a
我正在努力构建一个查询选择以前购买过另一种产品的用户(这与他们现在购买的不同)。 我想知道有多少用户购买了产品 B,之前购买了产品 A。
我的表如下所示:
User ID | Product ID | Date
1 | B | 2020/12/05
2 | B | 2020/12/04
1 | A | 2020/12/03
3 | A | 2020/12/03
3 | B | 2020/12/02
4 | B | 2020/12/02
4 | B | 2020/12/01
它应该交付结果为 1,因为用户 1 在 A 之后购买了 B。用户 3 在 B 之后购买了 A,因此不计算在内。 用户 4 只购买了产品 B,因此不计算在内。
如果您能提供帮助将非常高兴!
您可以使用聚合:
select count(*)
from (
select user_id
from mytable
group by user_id
having min(case when product_id = 'A' then date end)
< max(case when product_id = 'B' then date end)
) t
另一种方法是使用子查询和count(distinct)
:
select count(distinct user_id)
from mytable t
where product_id = 'B' and exists (
select 1 from mytable t1 where t1.user_id = t.user_id and t1.product_id = 'A' and t1.date < t.date
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.