2014-10-09 56 views
0

我有數據的表像這樣如何填寫總數爲零的查詢中的空白?

picks 
20 
20 
20 
18 
17 
12 
12 
9 
9 

這是表,但我需要得到這樣的。

Picks Count 
20  3 
19  0 
18  1 
17  1 
16  0 

...up to 

1  12 

我們如何編寫查詢以獲得表中不存在的數據的零總計?

阿倫

回答

2

使用子查詢產生的所有號碼,然後外其加入到你的表。

with nos as (select level as pick_id 
       from dual 
       connect by level <= 20) 
select nos.pick_id 
     , count(*) 
from nos 
    left outer join picks 
      on nos.pick_id = picks.id 
group by nos.pick_id 
order by nos.pick_id desc ;