[英]ONE SQL query to count records on different conditions
How can I count the total number of records, the number of unique of users and number of records on which the status is 2 from the table participants
in one query? 如何从一个查询的表
participants
中计算记录总数,用户唯一身份数和状态为2的记录数?
I know how to accomplish this using 3 separate queries: SELECT COUNT( ) FROM participants SELECT COUNT( ) FROM participants GROUP BY user SELECT COUNT(*) FROM participants WHERE status = 2 我知道如何使用3个独立的查询来完成此操作: 从参与者中选择COUNT( )从参与者中选择COUNT( )从用户中选择GROUP BY用户从状态中= 2的参与者中选择COUNT(*)
But this doesn't really seem efficient? 但这似乎并不有效吗?
Table participants
表
participants
id user status
10 john@example.com 1
11 john@example.com 1
12 john@example.com 1
13 sally@mailing.com 1
14 sally@mailing.com 2
15 edward@halloworld.com 1
16 edward@halloworld.com 1
17 edward@halloworld.com 2
18 mike@bestmail.net 2
19 mike@bestmail.net 1
29 nat@worldcom.com 0
Since you want just one result (per requirement), you don't need a group by
clause at all, and all of these requirements can be created as arguments for the count
function: 由于只需要一个结果(每个需求),因此根本不需要
group by
子句,并且所有这些需求都可以作为count
函数的参数创建:
SELECT COUNT(*) AS total_records,
COUNT(DISTINCT user) AS distinct_users_count,
COUNT(CASE status WHEN 2 ELSE NULL END) AS status_2_count
FROM participants
Just use conditional aggregation: 只需使用条件聚合:
select count(*) as numrecords, count(distinct user) as numusers,
sum(status = 2) as numstatus_2
from participants p;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.