Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count multiple columns with group by in one query

I count values from multiple columns like this:

SELECT COUNT(column1),column1 FROM table GROUP BY column1 SELECT COUNT(column2),column2 FROM table GROUP BY column2 SELECT COUNT(column3),column3 FROM table GROUP BY column3 

This returns for example for column1 array(attr1 => 2000, attr2 => 3000...) (Each column has specific and few values). The problem is that "table" in my application can be a query with some joins and where clauses, that may take 0.1sec. By doing all that counts "table" is computed each time again which is not necessary. Is there any way to take the results i want with one query, or "cache" the query that produces table? Otherwise i believe denormalization would be the only solution here. And i want the same results with the above queries. I am using mysql-myisam.

like image 636
user666 Avatar asked Oct 02 '12 15:10

user666


People also ask

Can we use GROUP BY and count together in SQL?

We can use GROUP BY to group together rows that have the same value in the Animal column, while using COUNT() to find out how many ID's we have in each group. It returns a table with three rows (one for each distinct animal).

Can we use count and GROUP BY together?

The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.

Can you GROUP BY multiple columns at once?

We can group the resultset in SQL on multiple column values. When we define the grouping criteria on more than one column, all the records having the same value for the columns defined in the group by clause are collectively represented using a single record in the query output.


2 Answers

It's hard to know how to help you without understanding the context / structure of your data, but I believe this might help you:

SELECT       SUM(CASE WHEN column1 IS NOT NULL THEN 1 ELSE 0 END) AS column1_count     ,SUM(CASE WHEN column2 IS NOT NULL THEN 1 ELSE 0 END) AS column2_count     ,SUM(CASE WHEN column3 IS NOT NULL THEN 1 ELSE 0 END) AS column3_count FROM table 
like image 108
coge.soft Avatar answered Oct 09 '22 18:10

coge.soft


One solution is to wrap it in a subquery

SELECT * FROM (     SELECT COUNT(column1),column1 FROM table GROUP BY column1     UNION ALL     SELECT COUNT(column2),column2 FROM table GROUP BY column2     UNION ALL     SELECT COUNT(column3),column3 FROM table GROUP BY column3 ) s 
like image 45
John Woo Avatar answered Oct 09 '22 17:10

John Woo