How can I 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 PersonalCount
FROM yourtable
GROUP BY distributor_id

Leave a Comment