2013-02-27 123 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