首页 > 试题广场 >

35.返回每个顾客不同订单的总金额 我们需要一个顾客 ID

[单选题]
35.返回每个顾客不同订单的总金额
我们需要一个顾客 ID 列表,其中包含他们已订购的总金额。
OrderItems表代表订单信息,OrderItems表有订单号:order_num和商品售出价格:item_price、商品数量:quantity
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
Orders表订单号:order_num、顾客id:cust_id
order_num cust_id
a0001 cust10
a0002
cust1
a0003
cust1
a0013
cust2
【问题】
编写 SQL语句,返回顾客 ID(Orders 表中的 cust_id),并使用子查询返回total_ordered 以便返回每个顾客的订单总数,将结果按金额从大到小排序。
提示:你之前已经使用 SUM()计算订单总数。

【示例结果】返回顾客id cust_id和total_order下单总额
cust_id total_ordered
cust2 2242
cust1 1300
cust10 1050
cust2 104
【示例解析】cust2在Orders里面的订单a0013,a0013的售出价格是2售出数量是1121,总额是2242,最后返回cust2的支付总额是2242。
  • 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 asc
  • select cust_id,avg(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
  • 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
  • select *
    from (OrderItems inner join Orders
    using(order_num))
我写到这直接提交了 题都搞得乱七八糟的不想写了
发表于 2023-07-13 16:55:32 回复(0)
为啥要right join
发表于 2024-03-16 17:21:56 回复(1)