這裏有一個辦法:
select t.type as "Type"
, sum(case when t.status = 'A' then 1 else 0 end) as "Count A"
, sum(case when t.status = 'I' then 1 else 0 end) as "Count I"
, sum(case when t.status = 'F' then 1 else 0 end) as "Count F"
from my_table t
group by t.type
order by t.type desc
這工作,如果你有你想要返回特定的列,並適用於「計數」行符合設置更復雜的標準。
[編輯]
(增加了DESC關鍵字,以得到有序的結果集如圖OP,+1良好的抓羅布麪包車Wijk!)
(Andomar使一個很好的觀察,更多的在結果集中有更多的列,使用這種方法,語句會變得不穩定,如果只有「測試」是對單個列進行相等比較,那麼獲得相同結果集還有其他方法可以很好地工作)。 Oracle 8i確實支持CASE表達式,不是嗎?如果我記得正確,Oracle 8沒有。我們可以去「老同學」做同樣的事情DECODE函數:
select t.type as "Type"
, sum(decode(t.status,'A',1,0)) as "Count A"
, sum(decode(t.status,'I',1,0)) as "Count I"
, sum(decode(t.status,'F',1,0)) as "Count F"
from my_table t
group by t.type
order by t.type DESC
[/編輯]
有時候,我們要檢查多種類型的條件,幷包括更多的行比一次計數。我們可以得到一個總
select t.type as "Type"
, sum(case when t.status in ('A') then 1 else 0 end) as "Count A"
, sum(case when t.status in ('I') then 1 else 0 end) as "Count I"
, sum(case when t.status in ('F') then 1 else 0 end) as "Count F"
, sum(case when t.status in ('A','I') then 1 else 0 end) as "#AI"
, sum(decode(sign(t.foo-t.bar),1,1,0)) as "#foo>bar"
, sum(decode(sign(10.0-t.foo),1,1,0)) as "#foo<10"
from my_table t
group by t.type
order by t.type desc
(只是想指出,有可能爲一排,以滿足多列指定的標準,所以它可能是「數」超過一次。有時候,這正是我們想要。)
+1雖然如果有超過100個不同的狀態,這會崩潰:) – Andomar 2009-06-03 20:20:30