我在 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 |
我想计算每天的现金流量,其中包括根据
in_flow
计算的现金的out_flow
和transaction_type
。想要的结果是:
日期 | in_flow | 输出流 |
---|---|---|
1697846400 | xxxxxxxxx | xxxxxxxxx |
1697500800 | xxxxxxxxx | xxxxxxxxx |
其中:
in_flow
= 所有 transaction value
与 transaction_type
的“卖出”的总和
date
out_flow
与 transaction value
的“购买”的总和 transaction_type
date
由
transaction value
计算为:
transaction_type
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;
交易:
in_flow | 输出流 | |
---|---|---|
空 | 13210541 |
buy
交易的条件改为
sell
,结果还是一样。当我只查询卖出交易时一切都很好:
LOWER(TRIM(t.transaction_type))='sell'
in_flow | |
---|---|
7197500 |
我尝试过:
更改查询中
Select date, sum(volume * price) - sum(commission) as in_flow
From transactions
Where transaction_type = 'sell' And date = 1697846400
Group By date;
in_flow
的顺序将out_flow
sell
LOWER(TRIM(t.transaction_type))='sell'
:
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()
演示在这里