如果为空或不返回,则将计数值返回为0

时间:2019-05-28 14:46:00

标签: oracle oracle-sqldeveloper

我正在数据库中运行以下查询,如果没有计数值,我试图将计数值重新返回0,但是这样做有问题。有人可以帮助您并说明如何实现

select state, count(phone_number) from VOIP_PHONE_NUMBER_POOL
where status = 3
group by state
order by state asc;

例如,当前我的查询正在返回类似的内容

State  Count

AZ     25

当我希望它返回空值并看起来像这样

State  Count

AZ     25
CA     0

3 个答案:

答案 0 :(得分:1)

这模仿了您现在拥有的东西:

SQL> with voip_phone_number_pool (state, phone_number, status) as
  2    (select 'AZ', 1234, 3 from dual union all
  3     select 'AZ', 2232, 3 from dual union all
  4     select 'AZ', 4444, 3 from dual union all
  5     select 'AZ', 7756, 1 from dual union all
  6     --
  7     select 'CA', 9999, 1 from dual
  8    )
  9  select state,
 10         count(phone_number)
 11  from voip_phone_number_pool
 12  where status = 3
 13  group by state
 14  order by state;

ST COUNT(PHONE_NUMBER)
-- -------------------
AZ                   3

SQL>

CA状态的行没有status = 3,因此该查询不会返回该行。

您可以做的是使用外部自连接这样的方式:

SQL> with voip_phone_number_pool (state, phone_number, status) as
  2    (select 'AZ', 1234, 3 from dual union all
  3     select 'AZ', 2232, 3 from dual union all
  4     select 'AZ', 4444, 3 from dual union all
  5     select 'AZ', 7756, 1 from dual union all
  6     --
  7     select 'CA', 9999, 1 from dual
  8    ),
  9  states as
 10    (select distinct state from voip_phone_number_pool)
 11  select s.state,
 12         count(v.phone_number)
 13  from states s left join voip_phone_number_pool v on v.state = s.state 
 14                                                  and v.status = 3
 15  group by s.state
 16  order by s.state;

ST COUNT(V.PHONE_NUMBER)
-- ---------------------
AZ                     3
CA                     0

SQL>
  • states CTE选择所有状态
  • 然后将其与voip_phone_number_pool进行外部联接
  • 请注意,条件(status = 3)必须移入连接(第14行);如果将其保留在where子句中,将不会得到预期的结果

答案 1 :(得分:0)

如果事实表(VOIP_PHONE_NUMBER_POOL)中没有任何具有特定状态的行,那么仅查询该表就不会得到这样的结果。

您需要将事实表连接到维度表(具有所有可能状态的表),以获得所需的计数。

例如,假设您有一个这样的维度表,它的名称为“ state_info”:

         SELECT s.state,
                COUNT(v.phone_number) AS phone_number_count
           FROM state_info s
LEFT OUTER JOIN voip_phone_number_pool v
                ON s.state = v.state
       GROUP BY s.state;

答案 2 :(得分:0)

     SELECT s.state,
            COUNT(v.phone_number) AS phone_number_count
       FROM CORP_ACCT s
       LEFT OUTER JOIN voip_phone_number_pool v
            ON s.state = v.state
   GROUP BY s.state; 

为我工作