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.