在下面的示例表中,我正在尝试找出一种方法来为ID中不存在标记“C”的所有标记对id进行求和。当ID中存在标记“C”时,我想要超过该ID的金额总和,不包括标记“A”的金额。如图所示,我想要的输出位于底部。我考虑过使用分区和EXISTS命令,但是我在构思解决方案时遇到了麻烦。如果你们中的任何一个人能够看一眼并指出我正确的方向,那将非常感激:)
样本表:
id mark amount
------------------
1 A 1
2 A 3
2 B 2
3 A 2
4 A 1
4 B 3
5 A 1
5 C 3
6 A 2
6 C 2
期望的输出:
id sum(amount)
-----------------
1 1
2 5
3 2
4 4
5 3
6 2
答案 0 :(得分:0)
select
id,
case
when count(case mark when 'C' then 1 else null end) = 0
then
sum(amount)
else
sum(case when mark <> 'A' then amount else 0 end)
end
from sampletable
group by id
答案 1 :(得分:0)
这是我的努力:
select id, sum(amount) from table t where not t.id = 'A' group by id
having id in (select id from table t where mark = 'C')
union
select id, sum(amount) from table t where t.id group by id
having id not in (select id from table t where mark = 'C')
答案 2 :(得分:0)
SELECT
id,
sum(amount) AS sum_amount
FROM atable t
WHERE mark <> 'A'
OR NOT EXISTS (
SELECT *
FROM atable
WHERE id = t.id
AND mark = 'C'
)
GROUP BY
id
;