同一个表上的MySQL多子查询

时间:2012-06-08 16:21:58

标签: mysql

我有一个以下结构的表

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

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

3 个答案:

答案 0 :(得分: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 Version(使用MySQL)

答案 1 :(得分: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

答案 2 :(得分: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
相关问题