SQL94. 返回每个顾客不同订单的总金额
描述
order_num | item_price | quantity |
a0001 | 10 | 105 |
a0002 | 1 | 1100 |
a0002 | 1 | 200 |
a0013 | 2 | 1121 |
a0003 | 5 | 10 |
a0003 | 1 | 19 |
a0003 | 7 | 5 |
order_num | cust_id |
a0001 | cust10 |
a0002 | cust1 |
a0003 | cust1 |
a0013 | cust2 |
cust_id | total_ordered |
cust2 | 2242 |
cust1 | 1300 |
cust10 | 1050 |
cust2 | 104 |
示例1
输入:
DROP TABLE IF EXISTS `OrderItems`; CREATE TABLE IF NOT EXISTS `OrderItems`( order_num VARCHAR(255) NOT NULL COMMENT '商品订单号', item_price INT(16) NOT NULL COMMENT '售出价格', quantity INT(16) NOT NULL COMMENT '商品数量' ); INSERT `OrderItems` VALUES ('a0001',10,105),('a0002',1,1100),('a0002',1,200),('a0013',2,1121),('a0003',5,10),('a0003',1,19),('a0003',7,5); DROP TABLE IF EXISTS `Orders`; CREATE TABLE IF NOT EXISTS `Orders`( order_num VARCHAR(255) NOT NULL COMMENT '商品订单号', cust_id VARCHAR(255) NOT NULL COMMENT '顾客id' ); INSERT `Orders` VALUES ('a0001','cust10'),('a0003','cust1'),('a0013','cust2');
输出:
cust2|2242.000 cust10|1050.000 cust1|104.000
Mysql 解法, 执行用时: 39ms, 内存消耗: 6440KB, 提交时间: 2022-07-21
select cust_id, sum(item_price*quantity) as total_ordered from OrderItems, Orders where OrderItems.order_num = Orders.order_num group by cust_id order by total_ordered desc; # select cust_id, # (select sum(item_price*quantity) # from OrderItems # where OrderItems.order_num = Orders.order_num # ) as total_ordered # from Orders # order by total_ordered desc;
Mysql 解法, 执行用时: 39ms, 内存消耗: 6448KB, 提交时间: 2022-03-07
select cust_id,sum(item_price*quantity) total_ordered from OrderItems a right join Orders b on a.order_num=b.order_num group by cust_id order by total_ordered desc
Mysql 解法, 执行用时: 39ms, 内存消耗: 6448KB, 提交时间: 2022-03-05
select cust_id, sum(quantity*item_price) as total_ordered from Orders,OrderItems where Orders.order_num=OrderItems.order_num group by cust_id order by total_ordered desc
Mysql 解法, 执行用时: 39ms, 内存消耗: 6500KB, 提交时间: 2022-03-04
SELECT cust_id, sum(quantity*item_price) FROM OrderItems natural JOIN Orders group by cust_id order by sum(quantity*item_price) desc
Mysql 解法, 执行用时: 39ms, 内存消耗: 6504KB, 提交时间: 2022-03-06
select cust_id,sum(item_price*quantity) as total_ordered from OrderItems JOIN Orders USING(order_num) GROUP BY cust_id,order_num ORDER BY total_ordered DESC