【问题标题】:skipping database records if count is 0如果 count 为 0,则跳过数据库记录
【发布时间】:2018-12-18 09:47:49
【问题描述】:

我有一个问题

 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

我需要如何编写查询? 提前谢谢..

【问题讨论】:

  • 不可能,因为没有 api_name 你没有行
  • 你的查询是正确的,你的输出是错误的。

标签: sql database postgresql count


【解决方案1】:

只需添加过滤掉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

【讨论】:

  • 是 api_name = 0 没有行返回。
  • @JoeTaras 你是对的。不可能有一个计数为零的输出
【解决方案2】:

假设api_namenull 值,那么你可以过滤掉它:

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

如果id 是数字类型,则不需要使用单引号。

【讨论】:

    【解决方案3】:

    您可能还需要考虑以下几点:

    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】:

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

      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 
      

      【讨论】:

        【解决方案5】:
        select count(api_name),api_name from abc_log where id = '1'
         group by api_name 
        having count(api_name) > 0 
        

        试一试。 George 的查询也可以正常工作。

        【讨论】:

          【解决方案6】:

          这个查询:

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

          只能api_nameNULL 时返回0 计数。 “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 ;
          

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

          【讨论】:

            猜你喜欢
            • 2020-05-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-10-05
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多