MySQL: 获取购买产品a后购买产品b的用户数

MySQL: Get number of users who bought product b AFTER they bought product a

我正在努力构建一个查询,以选择以前购买过另一种产品(与他们现在购买的产品不同)的用户。我想知道有多少用户购买了产品 B,之前购买了产品 A。

我的 table 看起来像这样:

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
)