How to get multiple counts with one SQL query? How to get multiple counts with one SQL query? sql sql

How to get multiple counts with one SQL query?


You can use a CASE statement with an aggregate function. This is basically the same thing as a PIVOT function in some RDBMS:

SELECT distributor_id,    count(*) AS total,    sum(case when level = 'exec' then 1 else 0 end) AS ExecCount,    sum(case when level = 'personal' then 1 else 0 end) AS PersonalCountFROM yourtableGROUP BY distributor_id


One way which works for sure

SELECT a.distributor_id,    (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,    (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,    (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCountFROM (SELECT DISTINCT distributor_id FROM myTable) a ;

EDIT:
See @KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for @Taryn♦'s answer. I'm leaving this so people can understand their options.


SELECT     distributor_id,     COUNT(*) AS TOTAL,     COUNT(IF(level='exec',1,null)),    COUNT(IF(level='personal',1,null))FROM sometable;

COUNT only counts non null values and the DECODE will return non null value 1 only if your condition is satisfied.