SQL Server - 列“在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中” [英] SQL Server - Column "invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause"
问题描述
我想在我的下面的SQL中显示列 B
,但是当我将它添加到查询时,它给了我以下错误:
列T2.B'
在选择列表中无效,因为它不包含在
聚合函数或GROUP BY子句中。
我的代码: 要么选择一个特定的值(例如 考虑以下数据: 查询 会返回: 这一切都很好。然而,请考虑以下(非法)查询,这会产生此错误: 其返回的数据集说明问题: 然而,以下两个查询清楚地表明了这一点,并且不会导致错误: 使用汇总 会返回: 将列添加到 会返回: I would like to display the column Column T2.B'
is invalid in the select list because it is not contained in either an
aggregate function or the GROUP BY clause. My code:
Put in other words, this error is telling you that SQL Server does not know which Either you want to select one specific value (e.g. the Consider the following data: The query would return: which is all well and good. However consider the following (illegal) query, which would produce this error: And its returned data set illustrating the problem:
However, the following two queries make this clear, and will not cause the error: Using an aggregate would return: Adding the column to the would return:
这篇关于SQL Server - 列“在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
<$ p $ (B)作为T1,B
从T2
WHERE ID = 1
GROUP BY A
换句话说,这个错误告诉你SQL Server不知道哪个 / em> B
以从组中选择。
MIN
, SUM
或
AVG
),在这种情况下,您将使用适当的聚合函数,或者您希望将每个值选择为新行(即包括<$ c
ID AB
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
$ c
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? 13和79都是分开的行吗? (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
P>
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
B
in my below SQL, but when I add it to the query it gives me the following error:
SELECT A, COUNT(B) as T1, B
FROM T2
WHERE ID=1
GROUP BY A
B
to select from the group. MIN
, SUM
, or AVG
) in which case you would use the appropriate aggregate function, or you want to select every value as a new row (i.e. including B
in the GROUP BY
field list).
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
listSELECT 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