You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL查询需求:关联两表计算订单总金额与基础金额

完善SQL查询获取目标结果表

现有数据表

Table A(费用明细)

orderNofeetypeamount
1shipping-10
1baseprice100
1commission-5
1discount-20
2commission-10
2discount-10
2shipping-20
2baseprice150

Table B(订单商品明细)

orderNocustomeritem
1Johnbeer
1Johnsoda
2Marycake
2Marycoffee
2Marypie

查询需求

需要编写SQL生成包含以下列的唯一订单结果表:

  • orderNo(唯一)
  • Total Amount:Table A中对应订单的所有amount之和
  • Customer Name:Table B中的客户名称
  • Base Amount:Table A中feetype为baseprice的amount值

目标结果表如下:

orderNocustomerbasepricetotal
1John10065
2Mary150110

现有部分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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 11:41:17