如果count为0,则跳过数据库记录

时间:2018-12-18 09:47:50

标签: sql database postgresql count

我有一个查询

 select count(api_name),api_name from abc_log where id = '1'
 group by api_name 

很好,我得到正确的结果。

假设我的输出是

 count       api_name

   1          abc
   10         123
   12         aaa
   0          xxx

但是我不需要获取计数为'0'的apinames

我该如何编写查询? 在此先感谢。

6 个答案:

答案 0 :(得分:0)

只需添加条件即可过滤出count(api_name)= 0

select count(api_name),api_name from abc_log where id = '1'
 group by api_name 
having count(api_name) <> 0

答案 1 :(得分:0)

您可以添加具有子句,如下所示:

select count(api_name),api_name from abc_log where id = '1'
group by api_name 
having count(api_name) > 0

如果您想让名称在0处消失,请尝试以下查询:

select count(api_name) count, 
  CASE count WHEN >0 THEN api_name ELSE ' ' END
from abc_log 
where id = '1'
group by api_name 

答案 2 :(得分:0)

假设api_name的值为null,则可以将其过滤掉:

select count(api_name), api_name 
from abc_log 
where id = 1 and api_name is not null
group by api_name; 

如果id具有数字类型,则无需使用单引号。

答案 3 :(得分:0)

您可能还需要考虑以下因素:

with T as (
    select count(api_name) count, api_name
    from abc_log
    where id = '1'
    group by api_name
)
select *
from T
where count > 0

答案 4 :(得分:0)

select count(api_name),api_name from abc_log where id = '1'
 group by api_name 
having count(api_name) > 0 

尝试一下。乔治的查询也可以正常工作。

答案 5 :(得分:0)

此查询:

select count(api_name), api_name 
from abc_log
where id = 1  -- guessing that id is a number
group by api_name ;
0api_name时,

只能 返回NULL作为计数。对于“ xxx”值,不会发生这种情况。

我的猜测是您的查询更加复杂。

对于此查询,我建议:

select count(api_name), api_name 
from abc_log
where id = 1 and -- guessing that id is a number
      api_name is not null
group by api_name ;

更通用的解决方案是使用having(其他人已经回答了):

select count(api_name), api_name 
from abc_log
where id = 1 and -- guessing that id is a number
      api_name is not null
group by api_name
having count(api_name) > 0 ;

但是,从性能和清晰度的角度来看,最好在聚合之前进行过滤。