如何将3个select语句组合成一个? (SQL Server 2008)

时间:2015-03-03 14:17:47

标签: sql sql-server stored-procedures

我有4个sql语句,每个语句返回2列

select count(id) open, sum(amount) from A where status = 1 group by est_id
  

结果:25 | 4400

select count(id) close, sum(amount) from A where status = 2 group by est_id
  

结果:0 | 0

select count(id) stop, sum(amount) from A where status = 3 group by est_id
  

结果:20 | 4000

我需要在一个中返回4 sql sql语句的结果,例如:

25 | 4400| active
0  | 0   | inactive
20 | 4000| close

问候

1 个答案:

答案 0 :(得分:1)

如@bluefeet所述,您正在寻找UNION ALL运营商。

select count(id) as c1, sum(amount) as c2, 'active' as c3 from A where status = 1 group by est_id
union all
select count(id), sum(amount), 'inactive' from A where status = 2 group by est_id
union all
select count(id), sum(amount), 'close' from A where status = 3 group by est_id

组合结果集中的列名将取自第一个组件结果集。