【问题标题】:SQL query to see changes in user types用于查看用户类型变化的 SQL 查询
【发布时间】:2018-10-16 05:07:10
【问题描述】:

在 [order] 表中,某些行具有相同的 user_id 但费用不同,这意味着它们会随着时间的推移从基本转换为高级,反之亦然。基本支付零费用,高级可以选择不同的月度订阅计划。

我正在尝试查看从一个计划切换到另一个计划的用户数量。我使用下面的查询来查看“基本用户数”。有没有办法为同一用户整合“where fee = 0”和“where fee >0”?

如果不是,我应该使用什么 SQL 语句来提取这些数字?

提前感谢您的帮助!

select count(distinct user_id)
from orders
where fee = 0 
and date::date > '2013-03-01'::date

【问题讨论】:

  • 您可以在 where 子句中添加 OR 条件以添加费用 > 0。应该可以。
  • 这个查询可能很棘手)ID 为 2 的样本数据中的用户是否应该算作切换用户,因为他有 2 条记录但费用为 0?
  • (1) 用您正在使用的数据库标记您的问题。 (2) 你想要什么输出?我不明白你在找什么。

标签: sql where-in


【解决方案1】:

我能想到几种方法。不知道哪个更有效。

使用子查询:

select count(distinct user_id)
from orders
where
  user_id in (select user_id from orders where fee = 0) and
  user_id in (select user_id from orders where fee > 0);

内联条件之一:

select count(distinct user_id)
from orders
where
  fee = 0 and
  user_id in (select user_id from orders where fee > 0);

使用相关子查询:

select count(distinct user_id)
from orders o1
where
  fee = 0 and
  exists (select * from orders o2 where o1.user_id = o2.user_id and o2.fee > 0);

使用自联接:

select count(distinct o1.user_id)
from orders o1
join orders o2 on o1.user_id = o2.user_id
where
  o1.fee = 0 and
  o2.fee > 0;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-11
    相关资源
    最近更新 更多