尝试遵循 SQL 中的 GROUP BY 逻辑
Trying to follow GROUP BY logic in SQL
我正在准备 SQL 面试,正在阅读本指南。
作者最终写的代码是:
SELECT cust_id,
first_name,
sum(total_order_cost)
FROM customers
JOIN orders ON customers.id = orders.cust_id
GROUP BY cust_id,
first_name
我的问题:
为什么在 GROUP_BY 中使用 first_name?如果我在 GROUP BY 中编写没有 first_name 的代码,我就会出错。
提前致谢。
SELECT
中的未聚合列(在本例中为 cust_id
和 first_name
)需要在 GROUP BY
中列出。即使在这种情况下,每个 cust_id
(大概)只有一个 first_name
,数据库引擎仍然期望 SELECT
中的每一列要么在聚合函数中,要么在GROUP BY
.
我正在准备 SQL 面试,正在阅读本指南。
作者最终写的代码是:
SELECT cust_id,
first_name,
sum(total_order_cost)
FROM customers
JOIN orders ON customers.id = orders.cust_id
GROUP BY cust_id,
first_name
我的问题: 为什么在 GROUP_BY 中使用 first_name?如果我在 GROUP BY 中编写没有 first_name 的代码,我就会出错。
提前致谢。
SELECT
中的未聚合列(在本例中为 cust_id
和 first_name
)需要在 GROUP BY
中列出。即使在这种情况下,每个 cust_id
(大概)只有一个 first_name
,数据库引擎仍然期望 SELECT
中的每一列要么在聚合函数中,要么在GROUP BY
.