0

我有这个 Oracle 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,因为数字的顺序必须严格。你能告诉我如何解决这个问题吗?

4

1 回答 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;
于 2013-02-27T20:06:00.800 回答