如何在SQL中高效地统计某些列值的出现次数?

2022-06-09 00:00:00 sql mysql data-modeling

我正在使用MySQL。

我有一个service_status表:

   id | service_id | service_status
   ----------------------------------------------------------------------
   0  | 1001       | download_started
   1  | 1001       | download_started
   2  | 1002       | download_started
   3  | 1002       | download_started
   4  | 1002       | download_failed
   5  | 1003       | download_started
   6  | 1003       | download_failed
   7  | 1003       | something_else
   8  | 1003       | another_thing

我要查询所有service_id,以及计算download_starteddownload_failed的数目的另外两列:

id | service id | download_started | download_failed
----------------------------------------------------------------------
0  | 1001       | 2                | 0
1  | 1002       | 2                | 1
2  | 1003       | 1                | 1

我只关心download_starteddownload_failed的状态。

非常感谢。


解决方案

您可以使用此命令:

SELECT 
    service_id,
    SUM(CASE WHEN service_status = 'download_started' THEN 1 ELSE 0 END) download_started,
    SUM(CASE WHEN service_status = 'download_failed' THEN 1 ELSE 0 END) download_failed
FROM 
    table_name
GROUP BY 
    service_id
ORDER BY 
    service_id;

相关文章