2016-01-22 31 views
-1

美好的一天。SQL:可能在一個案件內的案件內計數嗎?

下面是一個關於我試圖實現的圖像。

在一個表中有兩個字段,一個是ID,一個是Type。

我想出一張圖片描繪了千言萬語,所以請檢查下面

我試圖與案件和其他的東西了一些東西,但沒有奏效。

有幾件事要注意:由於某些限制,我們不能使用臨時表,插入或刪除。

Because using CTRL + K does not work in this situation

數據樣本:

ID Type 
3 bad 
2 zeal 
4 tro 
3 pol 
2 tro 
2 lata 
4 wrong 
3 dead 
2 wrong 
3 dead 
4 wrong 
3 lata 
2 bad 
2 zeal 
+1

請提供您的查詢...和小數據樣本。 – Devart

+0

@ Devart,在這一點上,我放棄了我試過的每一個查詢,我會附上一個數據樣本。 – Dansmith

+0

什麼是預期的結果? –

回答

3

,首先你需要包含類型組的表:

 
type typegroup 
bad  1 
tro  1 
zeal 1 
dead 2 
lata 2 
wrong 2 
pol  3 

然後加入,按類型分組,以獲得一個每個類型組的結果行數和計數。

select 
    tg.typegroup, 
    count(case when id = 2 then 1 end) as id2, 
    count(case when id = 3 then 1 end) as id3 
    count(case when id = 4 then 1 end) as id4 
from typegroups tg 
join mytable m on m.type = tg.type 
group by tg.typegroup 
order by tg.typegroup; 

UPDATE:當然,你可以創建即時這樣的表。

... 
from 
(
    select 'bad' as type, 1 as typegroup 
    union all 
    select 'tro' as type, 1 as typegroup 
    union all 
    ... 
) tg 
join mytable m on m.type = tg.type 
... 

如果您願意,可以將其移動到WITH子句中。

+0

無論如何,你可以想到這樣做,而沒有一個新的表?在這一點上,儘管你的答案看起來最可行。 – Dansmith

+0

當然,看看我的更新。 (當然,你也可以在輸入'bad','tro'...')的情況下對案例表達式進行分組,但在我看來,這樣做的可讀性會降低。 –

+0

此方法是否考慮到Koopa,Gumba和Toadstool的第一個結果行中的不同類型組? –