Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple counts with one SQL query?

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' 
like image 602
Crobzilla Avatar asked Oct 08 '12 21:10

Crobzilla


People also ask

Can we have multiple count in SQL?

You can count multiple COUNT() for multiple conditions in a single query using GROUP BY. SELECT yourColumnName,COUNT(*) from yourTableName group by yourColumnName; To understand the above syntax, let us first create a table.

How do you get a count of records in SQL query?

The SQL COUNT(), AVG() and SUM() FunctionsThe COUNT() function returns the number of rows that matches a specified criterion.

How do I SELECT multiple items in SQL query?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.


2 Answers

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 
like image 112
Taryn Avatar answered Sep 29 '22 03:09

Taryn


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 TotalCount FROM (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.

like image 32
NotMe Avatar answered Sep 29 '22 03:09

NotMe