I am wondering how to write this query.
I know this actual syntax is bogus, but it will help you understand what I am wanting. I need it in this format, because it is part of a much bigger query.
SELECT distributor_id,
COUNT(*) AS TOTAL,
COUNT(*) WHERE level = 'exec',
COUNT(*) WHERE level = 'personal'
I need this all returned in one query.
Also, it need to be in one row, so the following won't work:
'SELECT distributor_id, COUNT(*)
GROUP BY distributor_id'
For mysql this can be shorten to
You can use a
CASE
statement with an aggregate function. This is basically the same thing as aPIVOT
function in some RDBMS:Well, if you must have it all in one query, you could do a union:
Or, if you can do after processing:
You will get the count for each level and need to sum them all up to get the total.
Based on Bluefeet's accepted response with an added nuance using OVER ()
Using
OVER()
with nothing in the () will give you the total count for the whole dataset.I do something like this where I just give each table a string name to identify it in column A, and a count for column. Then I union them all so they stack. The result is pretty in my opinion - not sure how efficient it is compared to other options but it got me what I needed.
Result:
One way which works for sure
EDIT:
See @KevinBalmforth's break down of performance for why you likely don't want to use this method and instead should opt for @bluefeet's answer. I'm leaving this so people can understand their options.