0

我有以下结构的表

ID | Amount | Bank (1 or 2)
---+--------+------
1  | 100000 | 1
2  | 256415 | 2
3  | 142535 | 1
1  | 214561 | 2
2  | 123456 | 1
1  | 987654 | 2

我想要这样的结果(来自同一张表):

ID | sum(Bank 1) | sum(Bank 2)
---+-------------+------------
1  | 100000      | 1202215
2  | 123456      | 256415
3  | 142535      | 0

实现这一目标的最简单查询是什么?

4

3 回答 3

2

ANSI 解决方案:

Select Id
  , Sum( Case When Bank = 1 Then Amount End ) As Bank1Total
  , Sum( Case When Bank = 2 Then Amount End ) As Bank2Total
From SourceTable
Group By Id

SQL Fiddle 版本(使用 MySQL)

于 2012-06-08T16:37:20.053 回答
1

此 SQL 查询将提取您要查找的信息:

select ID, 
       SUM(IF(Bank=1, Amount, 0)) AS Bank1,
       SUM(IF(Bank=2, Amount, 0)) AS Bank2
from TableName
group by ID ASC
于 2012-06-08T16:31:22.940 回答
1

使用sqlFiddle和 tsql 我能够想出:

select distinct t.id,
      isnull((select sum(t1.amount) 
         from temp as t1
         where t.id = t1.id and t1.bank = 1), 0) as 'bank 1 sum',
      isnull((select sum(t1.amount) 
         from temp as t1
         where t.id = t1.id and t1.bank = 2), 0) as 'bank 2 sum'
  from temp as t

其中 temp 是您的表名。对于 mySQL(感谢评论中的@JakeFeasel):

select distinct t.id,
      ifnull((select sum(t1.amount) 
         from temp as t1
         where t.id = t1.id and t1.bank = 1), 0) as 'bank 1 sum',
      ifnull((select sum(t1.amount) 
         from temp as t1
         where t.id = t1.id and t1.bank = 2), 0) as 'bank 2 sum'
  from temp as t
于 2012-06-08T16:32:13.347 回答