sql - GROUP BY 限制示例

标签 sql

在 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/

相关文章:

java - JDBC SQL SELECT 查询总和方法行为不正确

sql - 从3张 table 中选择HIVE

mysql - 经常需要交集时存储多对多 SQL 关系的正确方法?

java - 在 hibernate 中使用 native 查询进行内连接

mysql - SQL 查询不起作用

sql - TSQL-重新排列代码中的sql作业步骤顺序

PostgreSQL存储过程,如何返回结果集

MySql 选择不工作

sql - Oracle SQL -- 查找不在表中的值

sql - Sqlite3中两个日期之间的差异