2011-09-22 33 views
0

我是新用戶,我認爲這太神奇了! 我需要一點幫助:Oracle - 在同一行中的count()

我這樣做,但不要像我想要的那樣工作! (計數(countOfCat)是沒有好!)

select count(countOfCat) as "Cat", count(countOfDog) as "dog", count(countOfHorse) as "horse", 0 as "duck", 0 as "Mouse" 
from animal 
where Birthdate in 
     (... 
     -- i think not important 
     ... 
     ) 
     and (species= 'cat' or species= 'dog' or species= 'horse') 
group by species 

我正在想收到這樣

 
Cat     Dog     Horse   Duck   mouse 
------- ------- ------- ------ ------- 
1234    2345    3456     0      0 

...

我需要所有的計數都在同行。
我不能利用這個

 
noGood- Cat Dog  Horse Duck mouse 
noGood- ----- ------ -------- ------- ------- 
noGood- 1234 0  0  0   0 
noGood- 0  2345 0  0   0 
noGood- 0  0  3456 0   0 

感謝您YOUT時間!
Da!

+0

您能否提供原始表格的示例數據? –

+0

是「物種」是你的專欄名稱?和「貓」,「狗」和「馬」是你的那一欄的價值? –

+0

@ Yagnesh:是的物種是一個專欄名稱,是的,貓狗和馬是我的價值觀種族專欄的一個子字符串。謝謝 @達里爾:這是一個大系統的一個小翻譯,我需要把這個選擇放在一個經過處理的視圖中,但是我希望這足以知道我有一張大桌子:「動物」有一列像「物種「,而貓狗馬鴨是物種的價值。 我有另一個重要的「出生日期」,我只能選擇2歲的動物(但我可以這樣做:D) 謝謝 – BellaVita

回答

1

我也覺得很奇妙,你是新來的。 :D

select 
    (select count(*) from animal a where a.species = 'cat') as Cat, 
    (select count(*) from animal a where a.species = 'horse') as Horse, 
    (select count(*) from animal a where a.species = 'duck') as Duck 
from 
    dual 

注意:dual是一個系統表,總是有一個單一的行。這樣的技巧非常方便。

+0

hI,謝謝!我嘗試這個代碼,但必須把這個選擇放在物化視圖和更多的工會所有...這改變了我的選擇結構,我有一個小問題。 :( – BellaVita

+0

您查詢表3次,只需要1次。a_horse_with_no_name有更好的解決方案 – winkbrace

+0

是的,這就是爲什麼我提高了他的答案並在那裏留下了評論。順便說一句,Oracle在優化這樣的查詢方面非常聰明,所以它實際上並沒有在表格上執行三個查詢。 – GolezTrol

6
select sum(case when species = 'cat' then 1 else 0 end) as "Cat", 
     sum(case when species = 'dog' then 1 else 0 end) as "Dog", 
     sum(case when species = 'horse' then 1 else 0 end) as "Horse", 
     0 as "duck", 
     0 as "Mouse" 
from animal 
where species in ('cat', 'dog', 'horse') 
+0

我非常感謝你,我正在嘗試你的代碼,但結果是兩行,我需要的結果是相同的「11 22 33 0 0「,我錯了嗎? – BellaVita

+0

我錯了!!!我按組種類!當我取消組工作時非常好!!!!:D:D:D謝謝!!!:D:D:D – BellaVita

+0

+1 – GolezTrol

0

很簡單。 您只需要移除group by子句即可:D

select count(countOfCat) as "Cat", count(countOfDog) as "dog", count(countOfHorse) as "horse", 0 as "duck", 0 as "Mouse" 
from animal 
where Birthdate in 
     (... 
     -- i think not important 
     ... 
     ) 
     and (species= 'cat' or species= 'dog' or species= 'horse') 
+0

真的嗎?我花了2個小時爲一個團體?ohhhhhhhh感謝你對everyBody!這頁是太棒了!:D – BellaVita