我有一个看起来像这样的数据库
users
email name state id
bill@domain.com Bill CA 1
Susan WY 2
jill@domain.com Jill CA 3
phil@domain.com Phil WY 4
您会注意到Susan没有电子邮件。
我正在尝试获取每个州的记录数,然后是每个州的非空电子邮件总数。
我能够得到这样的州总数:
SELECT state, COUNT(*) as count FROM users GROUP BY state
那很好。
然后我尝试获取这样的电子邮件总数:
SELECT state, COUNT(*) as count, COUNT(SELECT * FROM users WHERE email IS NOT NULL) as email_count FROM users GROUP BY state
但这返回了解析语法错误。
我正在尝试获取这样的返回数据集:
[
{state: 'CA', count: 2, email_count: 2},
{state: 'WY', count: 2, email_count: 1}
]
答案 0 :(得分:1)
尝试一下!
SELECT
state,
COUNT(*) AS total_count,
SUM(CASE WHEN email is not null then 1 ELSE 0 END) AS count_email_not_null
FROM users
GROUP BY state
它将为您提供预期的输出。