sql - 在 SQL 中执行减法/寻找平衡
问题描述
这里的 SQL 表:http ://sqlfiddle.com/#!9/abe1da/9
当前表:
年 | 月 | 类型 | 账户 | 数量 |
---|---|---|---|---|
2021 | 1 | 实际的 | 美国广播公司 | 20 |
2021 | 1 | 实际的 | 定义 | 30 |
2021 | 1 | 实际的 | 吉 | 40 |
2021 | 1 | 实际的 | X | 7 |
2021 | 1 | 实际的 | 是的 | 3 |
2021 | 1 | 实际的 | 最后 | 105 |
预期的
年 | 月 | 类型 | 账户 | 数量 |
---|---|---|---|---|
2021 | 1 | 实际的 | 美国广播公司 | 20 |
2021 | 1 | 实际的 | 定义 | 30 |
2021 | 1 | 实际的 | 吉 | 40 |
2021 | 1 | 实际的 | X | 7 |
2021 | 1 | 实际的 | 是的 | 3 |
2021 | 1 | 实际的 | 最后 | 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','def','ghi','x','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, month, type;
这是一个 db<>fiddle。
推荐阅读
- python - 标签未显示在 Matplotlib 中
- java - Java Spring - 在Controller类中捕获请求者IP地址
- ios - 如何在 CarPlay 的列表视图中删除云图标?
- java - android studio中的进度条没有更新
- python - 使用 Pandas 进行插值并使用时间戳而不是日期时间字符串存储时间序列数据?
- bash - Shell Globbing 中的条件字符 - Bash/Zsh
- c++ - 排序后如何将二维数组重置为原始形式?
- javascript - 显示部分相邻图像的 Slick Slide Carousel
- php - 升级 Laravel 5.6 的 Envoyer 部署失败引用不匹配的 PHP 版本
- r - readOGR(dsn,层)中的错误:找不到函数“readOGR”