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

如何修改SQL分组统计逻辑,实现Cash_Card交易金额拆分合并?

调整SQL语句实现Cash_Card交易拆分统计需求

我帮你梳理下调整思路,直接给你可用的SQL语句,再解释清楚每个部分的作用:

最终可用的SQL语句

SELECT 
    p.Payment_type,
    SUM(p.amount) AS Sales
FROM (
    -- 处理原有非Cash_Card的交易(Cash、Card、Cheque直接用原金额统计)
    SELECT 
        b.Payment_type,
        a.total_amount AS amount
    FROM sl_sales_trans_master a 
    INNER JOIN sl_payment_master b ON a.payment_type_id = b.payment_type_id 
    WHERE a.reading_master_id = @ReadingMasterID 
        AND b.Payment_type != 'Cash_Card'
    
    UNION ALL
    
    -- 把Cash_Card拆成Cash类型的记录,取对应的现金金额
    SELECT 
        'Cash' AS Payment_type,
        a.CashAmount AS amount
    FROM sl_sales_trans_master a 
    INNER JOIN sl_payment_master b ON a.payment_type_id = b.payment_type_id 
    WHERE a.reading_master_id = @ReadingMasterID 
        AND b.Payment_type = 'Cash_Card'
    
    UNION ALL
    
    -- 把Cash_Card拆成Card类型的记录,取对应的刷卡金额
    SELECT 
        'Card' AS Payment_type,
        a.CardAmount AS amount
    FROM sl_sales_trans_master a 
    INNER JOIN sl_payment_master b ON a.payment_type_id = b.payment_type_id 
    WHERE a.reading_master_id = @ReadingMasterID 
        AND b.Payment_type = 'Cash_Card'
) p
WHERE p.Payment_type IN ('Cash', 'Card', 'Cheque') -- 只保留报表需要的三种类型
GROUP BY p.Payment_type;

改动说明

  • 拆分Cash_Card交易:通过UNION ALL将一条Cash_Card交易拆成两条独立记录,分别对应Cash和Card类型,各自取对应的金额字段,完美匹配报表的拆分统计要求。
  • 兼容原有统计逻辑:对于原本的Cash、Card、Cheque交易,直接沿用原有的total_amount进行统计,完全不改变原有业务逻辑。
  • 过滤目标类型:最后通过WHERE子句只保留报表需要的三种支付类型,避免出现多余的Cash_Card类型记录。
  • 分组求和:最终按支付类型分组求和,得到你需要的Sales和Payment_type结果。

如果需要额外增加一行总计销售额,可以把GROUP BY p.Payment_type改成GROUP BY p.Payment_type WITH ROLLUP,这样会自动生成一行以NULL为类型的总计记录。

内容的提问来源于stack exchange,提问作者Prathap Gangireddy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 10:52:48