mysql是select语句中的子查询

时间:2017-09-27 22:33:09

标签: mysql

我正在尝试编写一个查询,其中用户按照他们使用的促销代码进行排序,并告诉我这些用户中有多少人有免费计划以及有多少人有付费计划。这是我的尝试。

select count(refer) as promo, (count(plan)
    from users
    where plan = 'free'
) as free, (count(plan)
    from users
    where plan <> 'free'
) as pay from users
where refer <> ''
group by refer

这不起作用,但我不确定要改变什么以使其发挥作用。

1 个答案:

答案 0 :(得分:0)

可以通过功能CASE

select count(refer) as promo, 
count(case when plan = 'free' then 1 end) as free
count(case when plan <> 'free' then 1 end) as pay
from users
where refer <> ''
group by refer