2013-02-27 87 views
0

我有這個,我用它來計算組件集成到Oracle表的SQL查詢:在SQL查詢返回數

select ct.name as component_type, count(1) as cnt from componentstats cs, componenttype ct 
WHERE CS.COMPONENTTYPEID = CT.COMPONENTTYPEID AND CT.COMPONENTTYPEID IN (1000, 1300, 4000) 
group by ct.name order by ct.name; 

這是輸出:

COMPONENT_TYPE                      CNT      
---------------------------------------------------------------------------------------------------- ---------------------- 
DATACENTER                       1      
ISP                         1      
NETWORK                        1      

我注意到,如果沒有組件與類型例如1300我得到兩個值1和1.我需要得到結果1,0,1,因爲數字的順序必須嚴格。你能告訴我如何解決這個問題嗎?

回答

3

你需要一個外連接。這是你應該使用標準ANSI連接語法的一個很好的理由。

您還需要將count()更改爲從外部聯接的「外部」部分進行計數。這裏是使用left outer join寫的查詢:

select ct.name as component_type, count(cs.componenttypeid) as cnt 
from componenttype ct left outer join 
    componentstats cs 
    on CS.COMPONENTTYPEID = CT.COMPONENTTYPEID 
where CT.COMPONENTTYPEID IN (1000, 1300, 4000) 
group by ct.name 
order by ct.name; 
+0

我可以再問你一件事。我如何只顯示沒有'name'的CNT作爲結果? – 2013-02-27 20:26:02

+0

@PeterPenzov。 。 。你並在'where'子句中添加'和cs.name = null'。 – 2013-02-27 20:27:01