题解必知必会38 | #返回顾客名称和相关订单号以及每个订单的总价#
返回顾客名称和相关订单号以及每个订单的总价
http://www.nowcoder.com/practice/4dda66e385c443d8a11570a70807d250
注意:这里审题错误,最后根据顾客名字和顾客订单号进行排序,如果不是因为这题每个顾客只有一个订单号,那就错了,审题一定要清楚啊。。。
这里题目描述也有点歧义,应该说每个顾客的订单总价,而不是每个订单的总价,一个顾客可能有多个订单,每个订单就不存在多个了
select cust_name , ord.order_num , sum(quantity * item_price) as OrderTotal from Customers as cus left join Orders as ord on cus.cust_id = ord.cust_id left join OrderItems as oi on ord.order_num = oi.order_num group by cust_name, cus.cust_id, ord.order_num(常见的错误就是会漏掉后面两个字段,一旦使用group by聚合了,select和order by后面的所有非聚合字段,都要用group by聚合一下, 这里有没有sum函数都一样,sum()属于聚合字段,不影响,我暂时理解是这样) order by cust_name, cus.cust_id这里收集一下经典报错的点
SQL_ERROR_INFO: "Expression #2 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'cus.cust_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by"
SQL_ERROR_INFO:“ORDER BY子句的表达式#2不在GROUP BY子句中,并且包含未聚合的列'cus.cust_id',该列在功能上不依赖GROUP BY子句中的列;这与SQL_mode=only_full_GROUP BY不兼容”
SQL_ERROR_INFO:“ORDER BY子句的表达式#2不在GROUP BY子句中,并且包含未聚合的列'cus.cust_id',该列在功能上不依赖GROUP BY子句中的列;这与SQL_mode=only_full_GROUP BY不兼容”
以上忘记group by cus.cust_id,故报错
r如果这里不用sum,也就不用group by了,只是可能不够全面,也能通过
select cust_name , ord.order_num , (quantity * item_price) from Customers as cus left join Orders as ord on cus.cust_id = ord.cust_id left join OrderItems as oi on ord.order_num = oi.order_num order by cust_name, cus.cust_id其他解法:子查询,先聚合,在三表连接,注意:这样group by就只用跟一个字段了,但是思路是完全不同的思路了https://blog.nowcoder.net/n/4fba279fc5994442b0fd16357d241a35?f=comment
select c.cust_name,t.order_num,t.OrderTotal from Orders o join (select order_num,sum(quantity*item_price) OrderTotal from OrderItems group by order_num) t on t.order_num=o.order_num join Customers c on c.cust_id=o.cust_id order by c.cust_name,t.order_num;