用于查看用户类型更改的SQL查询

时间:2018-05-06 05:17:47

标签: sql where-in

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

我试图看到用户数量从一个计划切换到另一个计划。我使用以下查询来查看基本用户的数量'。有没有办法以某种方式整合'其中费用= 0'和'其中费用> 0'对于同一个用户?

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

提前感谢您的帮助!

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

order

1 个答案:

答案 0 :(得分:0)

我可以想到几种方法。不知道哪一个更有效率。

使用子查询:

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;