如何重构此SQL查询?

kha*_*rul 1 mysql sql

我有一个名为userswith a column 的表activated_at,我想通过检查列是否为null来计算已激活的用户数.然后像这样并排显示它们:

+----------+-----------+---------------+-------+
| Malaysia | Activated | Not Activated | Total |
+----------+-----------+---------------+-------+
| Malaysia |      5487 |           303 |  5790 | 
+----------+-----------+---------------+-------+
Run Code Online (Sandbox Code Playgroud)

这是我的SQL:

select "Malaysia",
    (select count(*) from users where activated_at is not null and locale='en' and  date_format(created_at,'%m')=date_format(now(),'%m')) as "Activated",
    (select count(*) from users where activated_at is null and locale='en' and  date_format(created_at,'%m')=date_format(now(),'%m')) as "Not Activated",
    count(*) as "Total"
    from users 
    where locale="en"
    and  date_format(created_at,'%m')=date_format(now(),'%m');
Run Code Online (Sandbox Code Playgroud)

在我的代码中,我必须指定所有where语句三次,这显然是多余的.我怎么能重构这个?

此致,MK.

Dar*_*ler 6

不确定MySql是否支持CASE构造,但我通常通过做类似的事情处理这类问题,

select "Malaysia",
    SUM(CASE WHEN activated_at is not null THEN 1 ELSE 0 END) as "Activated",
    SUM(CASE WHEN activated_at is null THEN 1 ELSE 0 END as "Not Activated",
    count(*) as "Total"
from users 
where locale="en" and  date_format(created_at,'%m')=date_format(now(),'%m');
Run Code Online (Sandbox Code Playgroud)