sql - 在 SQL 中计算插头/余额
问题描述
我当前的表中有一些帐户在当前表中始终具有最小值(例如,X 和 Y 用于实际,AA、BB、CC 和 DD 用于计划)。具有最小值的帐户可以超出这些帐户。我需要将此类帐户分类为称为“余额”的代理帐户,该帐户始终为 [final-(abc+def+ghi)](请参阅预期表)。我正在尝试在 SQL 中使用
sum (case when account not in ('abc','def','ghi')
.
此处的示例数据集:http ://sqlfiddle.com/#!9/114cfe/1
SQL 尝试
select year, month, type,
case when accounts in 'abc' then 'abc'
case when accounts in 'def' then 'def'
case when accounts in 'ghi' then 'ghi'
case when accounts in 'final' then 'final'
else 'balance'
end as account_2
,
(
(case when accounts in ('abc','def','ghi','final') then sum(amount)
else
(
(case when accounts in ('final') then sum(amount))-
sum(case when accounts in ('abc','def','ghi') then sum(amount) else 0)))
)
解决方案
我认为将其分为两个步骤会更容易。在一个步骤中更改值并在另一个步骤中对行进行分组。
SELECT year, month, type, account_2, SUM(amount) AS amount_2
FROM (
SELECT year, month, type, amount,
CASE WHEN accounts IN ('abc', 'def', 'ghi', 'final') THEN accounts
ELSE 'balance' END AS account_2
FROM someTable
) AS tmp
GROUP BY year, month, type, account_2
推荐阅读
- windows - 通过批处理脚本中的匹配索引获取子字符串的位置
- google-cloud-firestore - Firestore 进行复合查询,但我需要一个查询
- sql - Oracle SQL Developer - 网格中每页的记录
- github - 在 GitHub 操作中评论拉取请求
- xcode - 当嵌入式框架之一禁用位码时,为什么 Xcode 不允许在启用位码的情况下进行编译?
- linux - Dockerfile 中的 sed 命令不会被执行或被覆盖
- python - 根据另一个 numpy 数组中的值查找 numpy 数组的索引
- mysql - 避免 SELECT 和 UPDATE 查询的损坏数据以及两者之间的长时间运行的任务
- javascript - 如何使用 d3 zoomBehavior 检测用户的平移和缩放?
- mysql - 在长查询中转换为系统时间