Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Group by multiple columns

Tags:

sql

sqlite

I have the following table

CREATE TABLE actions (id INTEGER PRIMARY KEY, key1 NUMERIC, key2 NUMERIC);

I'm not even sure how to explain this so I think it's best i give an example:

id  key1 key2
1   1    1
2   1    2
3   1    1
4   2    1
5   2    3

to ouput something like this:

key1 key2 count(id)
1    1    2
1    2    1
2    1    1
2    3    1  

I tried something like this, but it doesn't work, because i need the key1 field to not be unique :

Select  key1,key2,count(id)  from actions group by key2, order by key1

Thanks a lot

like image 308
Andrei Coman Avatar asked Apr 19 '11 11:04

Andrei Coman


2 Answers

SELECT key1, key2, COUNT(id) FROM actions GROUP BY key1, key2 ORDER BY key1, key2
like image 174
gcooney Avatar answered Oct 15 '22 08:10

gcooney


In the GROUP clause, you have to write all the fields that aren't in the agregate (COUNT, MAX, MIN). So, in this case, you need to add the key1 field, as this:

Select  key1, key2, count(id)  
from actions 
group by key1, key2 
order by key1
like image 34
eKek0 Avatar answered Oct 15 '22 09:10

eKek0