Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count occurrences of certain column value efficiently in SQL?

I am using MySQL.

I have a table of 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

I want to query for all service_ids, and two additional columns that count the number of download_started and number of download_failed:

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

I only care about the statuses that are download_started or download_failed.

Thanks a lot.

like image 454
rookie ninjia Avatar asked Dec 13 '25 20:12

rookie ninjia


1 Answers

You could use this:

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;
like image 176
Pham X. Bach Avatar answered Dec 16 '25 11:12

Pham X. Bach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!