Is it possible to GROUP BY multiple columns using MySQL?
MysqlSqlGroup ByMysql Problem Overview
Is it possible to GROUP BY
more than one column in a MySQL SELECT
query? For example:
GROUP BY fV.tier_id AND 'f.form_template_id'
Mysql Solutions
Solution 1 - Mysql
GROUP BY col1, col2, col3
Solution 2 - Mysql
Yes, you can group by multiple columns. For example,
SELECT * FROM table
GROUP BY col1, col2
The results will first be grouped by col1, then by col2. In MySQL, column preference goes from left to right.
Solution 3 - Mysql
Yes, but what does grouping by more two columns mean? Well, it's the same as grouping by each unique pair per row. The order you list the columns changes the way the rows are sorted.
In your example, you would write
GROUP BY fV.tier_id, f.form_template_id
Meanwhile, the code
GROUP BY f.form_template_id, fV.tier_id
would give similar results, but sorted differently.
Solution 4 - Mysql
group by fV.tier_id, f.form_template_id
Solution 5 - Mysql
To use a simple example, I had a counter that needed to summarise unique IP addresses per visited page on a site. Which is basically grouping by pagename and then by IP. I solved it with a combination of DISTINCT and GROUP BY.
SELECT pagename, COUNT(DISTINCT ipaddress) AS visit_count FROM log_visitors GROUP BY pagename ORDER BY visit_count DESC;
Solution 6 - Mysql
If you prefer (I need to apply this) group by two columns at same time, I just saw this point:
SELECT CONCAT (col1, '_', col2) AS Group1 ... GROUP BY Group1
Solution 7 - Mysql
GROUP BY CONCAT(col1, '_', col2)