SQLite Case When子句无法正常工作

mum43rcc  于 12个月前  发布在  SQLite
关注(0)|答案(1)|浏览(193)

我在SQLite中有一个这样的transactions表:
| ID|日期|交易类型|体积|价格|委员会|
| --|--|--|--|--|--|
| 65 | 1697846400 |买| 100 | 32000 | 1600 |
| 66 | 1697846400 |买| 100 | 2300 | 69 |
| 67 | 1697846400 |买| 100 | 2300 | 69 |
| 68 | 1697846400 |买| 100 | 23456 | 703 |
| 69 | 1697846400 |卖| 100 | 20000 | 600 |
| 70 | 1697846400 |卖| 100 | 20000 | 600 |
| 71 | 1697846400 |卖| 100 | 20000 | 1000 |
| 72 | 1697846400 |卖| 100 | 12000 | 300 |
我想计算每天的现金流,其中包括基于transaction_type计算的现金的in_flowout_flow。所需的结果是:
| 日期|流入|流出|
| --|--|--|
| 1697846400 |xxxxxxxxx| xxxxxxxxx|
| 1697500800 |xxxxxxxxx| xxxxxxxxx|
其中:

  • in_flow =所有transaction valuedate的“卖出”的transaction_type之和
  • out_flow =所有transaction valuetransaction_type的“购买”date的总和

transaction valuetransaction_type计算为:

  • buyvolume * price + commission
  • sellvolume * 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;

字符串
但它只适用于buy事务:
| 日期|流入|流出|
| --|--|--|
| 1697846400 |NULL| 13210541 |
我尝试将sell事务的条件更改为LOWER(TRIM(t.transaction_type))='sell',结果仍然相同。
当我只查询卖出交易时,一切都很好:

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


| 日期|流入|
| --|--|
| 1697846400 | 7197500 |
知道我做错了什么吗
我试探着:

  • 在查询中更改in_flowout_flow的顺序
  • sell事务的条件更改为LOWER(TRIM(t.transaction_type))='sell'
qni6mghb

qni6mghb1#

下面是一个使用聚合函数MAX()的方法:

SELECT date,
       MAX(CASE WHEN transaction_type = 'sell' THEN total_price - commission END) AS in_flow,
       MAX(CASE WHEN transaction_type = 'buy' THEN total_price + commission END) AS out_flow
FROM (
  SELECT date, transaction_type, sum(commission) as commission, sum(volume * price) as total_price
  FROM 
    transactions
  GROUP BY date, transaction_type
) AS S
GROUP BY date;

字符串
使用你的方法,CASE子句必须在聚合函数SUM()内部,而不是相反:

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


测试结果:
| 日期|流入|流出|
| --|--|--|
| 1697846400 | 7197500 | 6008041 |
Demo here

相关问题