2

在下面的示例表中,我试图找出一种方法来对 id 中不存在标记“C”的所有标记求和。当 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
4

3 回答 3

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
于 2012-10-31T21:56:07.563 回答
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')
于 2012-10-31T22:02:21.460 回答
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
;
于 2012-10-31T22:12:20.477 回答