简体   繁体   English

SQL Group由多列组成

[英]SQL Group by multiple columns

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 : 我试过这样的东西,但它不起作用,因为我需要key1字段不是唯一的:

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

Thanks a lot 非常感谢

SELECT key1, key2, COUNT(id) FROM actions GROUP BY key1, key2 ORDER BY key1, key2

In the GROUP clause, you have to write all the fields that aren't in the agregate (COUNT, MAX, MIN). 在GROUP子句中,您必须写入不在agregate(COUNT,MAX,MIN)中的所有字段。 So, in this case, you need to add the key1 field, as this: 因此,在这种情况下,您需要添加key1字段,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM