sql-server – 列“在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中”

我想在我的下面的SQL中显示列B,但是当我添加到查询它给我以下错误:

Column T2.B’
is invalid in the select list because it is not contained in either an
aggregate function or the GROUP BY clause.

我的代码:

SELECT A, COUNT(B) as T1, B 
FROM T2 
WHERE ID=1 
GROUP BY A 
换句话说,这个错误告诉你SQL Server不知道从组中选择哪个B.

要么选择一个特定值(例如MIN,SUM或AVG),在这种情况下,您将使用适当的聚合函数,或者要选择每个值作为新行(即在GROUP BY字段列表中包括B )。

考虑以下数据:

ID  A   B
1   1  13
1   1  79
1   2  13
1   2  13
1   2  42

查询

SELECT A, COUNT(B) AS T1 
FROM T2 
GROUP BY A

将返回:

A  T1
1  2
2  3

这是好和好。

但是,请考虑以下(非法)查询,这将产生此错误:

SELECT A, COUNT(B) AS T1, B 
FROM T2 
GROUP BY A

它返回的数据集说明了问题:

A  T1  B
1  2   13? 79? Both 13 and 79 as separate rows? (13+79=92)? ...?
2  3   13? 42? ...?

但是,以下两个查询使此清楚,并且不会导致错误:

>使用聚合

SELECT A, COUNT(B) AS T1, SUM(B) AS B
FROM T2
GROUP BY A

将返回:

A  T1  B
1  2   92
2  3   68

>将列添加到GROUP BY列表

SELECT A, COUNT(B) AS T1, B
FROM T2
GROUP BY A, B

将返回:

A  T1  B
1  1   13
1  1   79
2  2   13
2  1   42
http://stackoverflow.com/questions/18258704/column-invalid-in-the-select-list-because-it-is-not-contained-in-either-an-aggr

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:sql-server – 列“在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中”