How to get multiple counts with one SQL query?

The Solution to How to get multiple counts with one SQL query? is


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

~ Answered on 2012-10-08 21:07:34


Most Viewed Questions: