SQL 按多列分组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5715583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 10:12:04  来源:igfitidea点击:

SQL Group by multiple columns

sqlsqlite

提问by Andrei Coman

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

非常感谢

回答by gcooney

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

回答by eKek0

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

在 GROUP 子句中,您必须编写所有不在聚合中的字段(COUNT、MAX、MIN)。因此,在这种情况下,您需要添加 key1 字段,如下所示:

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