SQLite Case When 子句无法正常工作

问题描述 投票:0回答:1

我在 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;

交易:


日期1697846400
in_flow 输出流
13210541
我尝试将
buy

交易的条件改为

sell
,结果还是一样。
当我只查询卖出交易时一切都很好:

LOWER(TRIM(t.transaction_type))='sell'


日期1697846400
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
    
        
sqlite sum case
1个回答
0
投票
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()

演示在这里

© www.soinside.com 2019 - 2024. All rights reserved.