[英]what is sql command for this group by?
我有一个带有此列的表:“ id,Nationalcode,Ccode,Ocode,Adate,...”,现在我要在Nationalcode上进行分组, select id,Kasset from allocate group by Kasset
但是对于每个国家代码,都有几条记录,因此会导致以下错误: Column 'allocate.Id' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
什么是正确的命令?
从错误消息中已经很清楚了
选择列表中的“ allocate.Id”列无效,因为它既不包含在聚合函数中也不在GROUP BY子句中
同时具有多个 Allocate.Id
值的情况,例如
1, 2, 3
您必须借助聚合函数找出一个 :
1, 2, 3 -> SUM() -> 6
1, 2, 3 -> AVG() -> 2
1, 2, 3 -> MIN() -> 1
1, 2, 3 -> MAX() -> 3
1, 2, 3 -> COUNT() -> 3
等等。查询应该是
select Max(Id), --TODO: Put the right function here
Kasset
from Allocate
group by Kasset
编辑 :根据示例,让我们尝试找出这些聚合函数 (至少其中一些)(请参阅下面的评论)
id | Nationalcode | Ccode | Ocode | Kasset | Adat
-------------------------------------------------------
1 | 547 | 1910 | 1 | 4444 | 1995/09/27
2 | 546 | 1910 | 1 | 2222 | 1995/12/14
1 | 546 | 1910 | 1 | 4444 | 1995/01/01
理想的结果是
1 | 546 | 1910 | 1 | 4444 | 1995/09/27
2 | 546 | 1910 | 1 | 2222 | 1995/12/14
查询可以是
select Max(Id), -- ? Many options, Max among them
Min(Nationalcode), -- since 546, 547 -> 546
Max(Ccode), -- ? Many options, Max among them
Max(Ocode), -- ? Many options, Max among them
Kasset, -- ? Many options, Max among them
Max(Adat) -- 1995/09/27, 1995/01/01 -> 1995/09/27
from Allocate
group by Kasset
GROUP BY子句始终与聚合函数(即SUM,COUNT,MIN,MAX或AVG函数)一起使用
尝试这个:
select count(id) [Count], Kasset from allocate group by Kasset
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.