2011-03-21 96 views
1

比方說,我在MSSQL表收集有關在單個查詢表中的多個統計

 
type  status  
a   open 
b   open 
a   closed 
a   closed 
a   closed 
b   open 
c   closed 

我可以運行此查詢來獲取一個表像這樣
select type,count(*) from table where status = 'open'

 
a  1 
b  2 
有這樣的數據

然後我可以做另一個查詢
select type,count(*) from table where status = 'closed'

 
a   2 
c   1 

如何編寫一個查詢,顯示我這樣

 
type  open   closed 
a   1    2 
b   2    0 
c   0    1 

回答

3

這樣的表會產生你想要的結果

select type, 
    SUM(case when status = 'open' then 1 else 0 end) as [Open], 
    SUM(case when status = 'closed' then 1 else 0 end) as [Closed] 
from table 
group by type 
0

您可以使用PIVOT,看看在BOL或搜索任何SQL網站的一些使用示例。

+1

說實話鮑勃答案是不是「PIVOT」一個更容易實現,因此與該走了。 – Tony 2011-03-21 22:36:53

+0

鮑勃的答案只能在最微不足道的情況下實現。 – 2011-03-21 22:49:11

+1

@Eric - 我不同意。我傾向於發現「PIVOT」僅限於微不足道的情況。如果你想開始引入多個聚合 - 你不能。 – 2011-03-21 23:26:36

0

創建你的表在SQL 2005,並確認了以下作品使用轉動命令:

select * 
from (select type, status from table) test 
pivot (count(status) for status in ([Open], [Closed])) pivottable