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'
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'
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.
GROUP BY
applies col1+col2
. e.g. col1 = 1, 2, 1, 2 | col2 = 1, 2, 3, 2
and running GROUP BY col1,col2
would return 1,1|1,3|2,2
as opposed to 1,1|2,2
as suggested. Whereas GROUP BY col2, col1
would change the ascending order of col2 returning. 1,1|2,2|1,3
Demo: sqlfiddle.com/#!9/d5f69/1 Note that row id: 2 is returned in both cases for 2,2
despite inverting the columns.
GROUP BY
). And if in the first defined column there are equal results, then only within the equal results sorts by the second defined column
Commented
Jun 15, 2019 at 6:17
SUM
using with GROUP BY
. If GROUP BY
only by one column, then SUM
s all values of each distinct (different) the column value sqlfiddle.com/#!9/1cbde2/2. If GROUP BY
two columns. Then mysql at first checks if for the first column value there are different values in the second column. If yes, then mysql SUM
each different value of the second column sqlfiddle.com/#!9/1cbde2/1.
Commented
Jun 15, 2019 at 6:37
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.
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
SELECT CONCAT(col1, '_', col2) FROM GROUP BY col1, col2
. The results will usually look the same as this answer, but the internal execution is quite different.
Commented
Mar 6, 2019 at 13:25
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;
Yes, you can group by multiple column in query
GROUP BY fV.tier_id, f.form_template_id
GROUP BY CONCAT(col1, '_', col2)
GROUP BY col1, col2
. It will give wrong results with some data. Say col1, col2
have values: ('a_b', 'c')
in one row and ('a', 'b_c')
in another. This wrong answer, with GROUP BY CONCAT will aggregate the two rows in one. The correct answer will not.
Commented
May 17, 2017 at 15:49
SELECT CONCAT(col1, '_', col2) ... FROM ... GROUP BY col1, col2 ;
Commented
May 17, 2017 at 15:51