【问题标题】:MySQL: Get number of users who bought product b AFTER they bought product aMySQL:获取购买产品 a 后购买产品 b 的用户数量
【发布时间】:2021-03-17 07:39:00
【问题描述】:

我正在努力构建一个查询来选择以前购买过另一种产品的用户(这与他们现在购买的不同)。我想知道有多少用户购买了产品 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,因此不计算在内。

如果您能提供帮助将非常高兴!

【问题讨论】:

标签: mysql sql count subquery having-clause


【解决方案1】:

你可以使用聚合:

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
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多