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

SQLite中CASE WHEN子句计算现金流异常问题排查

SQLite按日期计算现金流时in_flow为NULL的问题

表结构与数据

SQLite中有一张transactions表,结构及数据如下:

iddatetransaction_typevolumepricecommission
651697846400buy100320001600
661697846400buy100230069
671697846400buy100230069
681697846400buy10023456703
691697846400sell10020000600
701697846400sell10020000600
711697846400sell100200001000
721697846400sell10012000300

需求

按日期计算现金流,包含in_flow和out_flow:

  • in_flow:当日transaction_type为'sell'的所有交易价值之和
  • out_flow:当日transaction_type为'buy'的所有交易价值之和

交易价值计算规则:

  • buy类型:volume * price + commission
  • sell类型:volume * price - commission

错误的查询语句

编写的查询语句如下:

SELECT t.date,
    CASE 
        When t.transaction_type = 'sell' THEN 
            sum(t.volume * t.price) - sum(t.commission)
    END as in_flow,
    Case
        When t.transaction_type = 'buy' Then 
            sum(t.volume * t.price) + sum(t.commission)
    End as out_flow
From 
    transactions as t
WHERE
    date = 1697846400
Group By t.date;

查询结果问题

结果中仅out_flow计算正确,in_flow为NULL:

datein_flowout_flow
1697846400NULL13210541

尝试过把sell的判断改为LOWER(TRIM(t.transaction_type))='sell',调整in_flow和out_flow的顺序,都没解决问题。但单独查询sell类型交易时结果正常:

Select date, sum(volume * price) - sum(commission) as in_flow
From transactions
Where transaction_type = 'sell' And date = 1697846400
Group By date;

结果:

datein_flow
16978464007197500

请问我哪里出错了?


问题原因及修正

问题出在聚合函数和CASE语句的顺序搞反了。

原查询中,先判断transaction_type再做聚合,但按date分组后,transaction_type不是分组字段,SQLite会随机选取分组内某一行的transaction_type值触发CASE判断,导致只会计算其中一种类型的流量,另一个字段返回NULL。

正确的做法是把CASE语句嵌套在SUM函数内部,先对每行按交易类型计算对应价值,再聚合求和。

修正后的查询语句

SELECT 
    t.date,
    SUM(CASE WHEN t.transaction_type = 'sell' THEN (t.volume * t.price - t.commission) ELSE 0 END) AS in_flow,
    SUM(CASE WHEN t.transaction_type = 'buy' THEN (t.volume * t.price + t.commission) ELSE 0 END) AS out_flow
FROM 
    transactions AS t
WHERE
    date = 1697846400
GROUP BY 
    t.date;

执行该语句后,会正确得到in_flow=7197500、out_flow=13210541的结果。

内容的提问来源于stack exchange,提问作者Tân Lê

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 00:18:10