SQL查询需求:关联两表计算订单总金额与基础金额
完善SQL查询获取目标结果表
现有数据表
Table A(费用明细)
| orderNo | feetype | amount |
|---|---|---|
| 1 | shipping | -10 |
| 1 | baseprice | 100 |
| 1 | commission | -5 |
| 1 | discount | -20 |
| 2 | commission | -10 |
| 2 | discount | -10 |
| 2 | shipping | -20 |
| 2 | baseprice | 150 |
Table B(订单商品明细)
| orderNo | customer | item |
|---|---|---|
| 1 | John | beer |
| 1 | John | soda |
| 2 | Mary | cake |
| 2 | Mary | coffee |
| 2 | Mary | pie |
查询需求
需要编写SQL生成包含以下列的唯一订单结果表:
- orderNo(唯一)
- Total Amount:Table A中对应订单的所有amount之和
- Customer Name:Table B中的客户名称
- Base Amount:Table A中feetype为
baseprice的amount值
目标结果表如下:
| orderNo | customer | baseprice | total |
|---|---|---|---|
| 1 | John | 100 | 65 |
| 2 | Mary | 150 | 110 |
现有部分SQL
已写出能生成前3列的SQL语句:
SELECT c.customer, a.orderNo, Sum(a.amount) AS [total] FROM a INNER JOIN (SELECT DISTINCT orderNo, customer FROM table b) AS c ON a.orderNo = c.orderNo GROUP BY c.customer, a.orderNo;
完善后的SQL
通过条件聚合函数可以快速获取baseprice列,完善后的SQL如下:
SELECT a.orderNo, c.customer, SUM(CASE WHEN a.feetype = 'baseprice' THEN a.amount ELSE 0 END) AS baseprice, SUM(a.amount) AS total FROM a INNER JOIN (SELECT DISTINCT orderNo, customer FROM table b) AS c ON a.orderNo = c.orderNo GROUP BY a.orderNo, c.customer;
关键说明
- 用
SUM(CASE WHEN a.feetype = 'baseprice' THEN a.amount ELSE 0 END)筛选每个订单的基准价,由于每个订单仅存在一条baseprice记录,求和结果即为对应金额。 - 调整了列的输出顺序,与目标表结构完全匹配。
- 分组字段保持
orderNo和customer的组合,确保每个订单唯一输出。
内容的提问来源于stack exchange,提问作者Merlin
相关产品推荐
相关产品推荐

