2015-03-03 61 views
0

我有4個SQL語句,每個返回2列如何將3個選擇語句合併爲一個? (SQL Server 2008中)

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 

問候

+3

查看'UNION ALL'或者如果表格是相同的,那麼添加一個'group by status','where status in(1,2,3)' – Taryn 2015-03-03 14:19:02

回答

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 

組合結果集中的列名將取自第一個組件結果集。

相關問題