在 SQL 中执行减法/找到平衡

问题描述

此处的 sql 表:http://sqlfiddle.com/#!9/abe1da/9

当前表:

年份 输入 账户 数量
2021 1 实际 abc 20
2021 1 实际 def 30
2021 1 实际 ghi 40
2021 1 实际 X 7
2021 1 实际 Y 3
2021 1 实际 final 105

预期

年份 输入 账户 数量
2021 1 实际 abc 20
2021 1 实际 def 30
2021 1 实际 ghi 40
2021 1 实际 X 7
2021 1 实际 Y 3
2021 1 实际 final 105
2021 1 实际 平衡 5

sql 尝试

select year,month,type,case when accounts in ('abc') then 'abc'
 when accounts in ('def') then 'def'
 when accounts in ('ghi') then 'ghi'
 when accounts in ('X') then 'x'
 when accounts in ('Y') then 'Y'
 when accounts in ('final') then 'final'
else 'balance'
end as account_2,sum
(
(case when accounts in ('abc','def','ghi','final','x','y') then amount
else 
(
(case when accounts in ('final') then (amount))-
(case when accounts in ('abc','y') then -amount else 0))
)
from new

注意:余额 5 代表数千个目前不构成数据库一部分的小账户。

解决方法

如果我理解正确:

select Year,Month,Type,Accounts,Amount
from new
union all
select year,month,type,'balance',(sum(case when accounts = 'final' then amount else 0 end) -
        sum(case when accounts <> 'final' then amount else 0 end) 
       )
from new
group by year,type;

Here 是一个 dbfiddle。