Sql 误解查询中按原因分组的必要性
我认为不需要样本数据来理解这个问题。我正在编写一个查询,以确定与每个客户关联的业务,如下所示:Sql 误解查询中按原因分组的必要性,sql,group-by,Sql,Group By,我认为不需要样本数据来理解这个问题。我正在编写一个查询,以确定与每个客户关联的业务,如下所示: select customers.cust_id, sum(OrderItems.Quantity * OrderItems.Item_Price) as total_business from Customers left outer join Orders on Customers.cust_id = orders.cust_id le
select
customers.cust_id,
sum(OrderItems.Quantity * OrderItems.Item_Price) as total_business
from
Customers
left outer join
Orders on Customers.cust_id = orders.cust_id
left outer join
OrderItems on orders.order_num = orderitems.order_num
-- group by Customers.cust_id -- why do I need this if I'm just trying to access the cust_id column?
order by total_business
如果我只是想访问
cust\u id
列,我不明白为什么需要使用groupby
子句。我的印象是,我可以访问(select
)属于新表的任何列。,因为不能将常规列选择与聚合函数(如sum()
)混合使用
只能使用聚合或普通列,或按列分组,其余部分使用聚合
例如:
food table
------------
name type
------------
tomato vegetables
mango fruits
kiwi fruits
potato vegetables
现在,如果你想知道食物的名称,那么使用
select name from food
如果你想要水果的数量那么
select count(type) from food where type = 'fruits'
但是如果你想知道每种食物的数量,那就去做吧
select type, count(*) from food group by type
因为您不能将普通列选择与聚合函数(如
sum()
)混合使用
只能使用聚合或普通列,或按列分组,其余部分使用聚合
例如:
food table
------------
name type
------------
tomato vegetables
mango fruits
kiwi fruits
potato vegetables
现在,如果你想知道食物的名称,那么使用
select name from food
如果你想要水果的数量那么
select count(type) from food where type = 'fruits'
但是如果你想知道每种食物的数量,那就去做吧
select type, count(*) from food group by type
如果没有Group By,您的结果集将为每个客户的每个订单都有一行。您希望每个客户都有一行,以及该客户所有订单的扩展价格之和。如果没有Group By,您的结果集将为每个客户的每个订单都有一行。您希望每个客户都有一行,以及该客户所有订单的扩展价格之和。+1这是一个很好的解释,但我现在正在重新考虑,因为您刚才让我浪费了三分钟时间试图弄清楚土豆是否真的是蔬菜。:)+谢谢你的精彩解释,但我现在正在重新考虑,因为你刚才让我浪费了三分钟的时间试图弄清楚土豆是否真的是蔬菜