在 postgreSQL 文档中,它说:
When GROUP BY is present, it is not valid for the SELECT list expressions to refer to ungrouped columns except within aggregate functions or if the ungrouped column is functionally dependent on the grouped columns, since there would otherwise be more than one possible value to return for an ungrouped column
我不明白关于“
there would otherwise be more than one possible value to return for an ungrouped column
”的部分。有人可以给我举个例子吗?如何为取消分组的列返回不止一个可能的值?
最佳答案
考虑这个表:
col_1 | col_2 | col_3
A 10 10
A 11 20
B 20 40
C 40 60
并尝试运行对 col_3 的值求和的此查询
SELECT col_1, col_2, SUM(col_3)
FROM t1
GROUP BY col_1
上面的查询可以有 2 个可能的输出:
Output 1: Here, col_2 = 10
---------------------------
col_1 | col_2 | SUM(col_3)
A 10 30
B 20 40
C 40 60
Output 2: Here, col_2 = 11
---------------------------
col_1 | col_2 | SUM(col_3)
A 11 30
B 20 40
C 40 60
这是因为 col_2 未包含在 GROUP BY 子句中。 col_3 上的求和基于 col_1 的分组按预期发生,但现在 SQL 引擎不知道您是否希望 A 的行的 col_2 为 11 或为 11。因此,“否则将有多个可能的值返回对于未分组的列”
上述查询适用于 MySQL,它将随机返回上述 2 个输出之一,而 Oracle/SQL Server 将抛出您提到的错误
关于sql - GROUP BY 限制示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15845658/