【问题标题】:Counting rows in SQL with multiple AND & OR statements使用多个 AND & OR 语句计算 SQL 中的行数
【发布时间】:2014-10-29 02:31:53
【问题描述】:

我正在尝试按创建它们的日期范围以及它们是否是多个邮政编码之一来计算数据库中的行数。从语义上讲,我想说的是统计这段时间内来自这些邮政编码的所有投诉。我的查询看起来像这样,

select COUNT(*) from complaints where created_date::date >= '2013-10-03' AND created_date::date <= '2014-05-31' AND incident_zip = 11209 OR incident_zip = 11201 OR incident_zip = 11202;

如果没有OR 语句使AND 语句毫无意义,我似乎无法运行查询。有人能解释一下如何对它进行分组,以便OR 语句只影响incident_zip 列而不影响created_date 列吗?

【问题讨论】:

    标签: ruby-on-rails database postgresql where


    【解决方案1】:

    在这种情况下,不需要包含incident_zip 的多个子句。相反,使用IN 子句将它们组合在一起:

    select COUNT(*)
    from complaints
    where created_date::date >= '2013-10-03'
      AND created_date::date <= '2014-05-31'
      AND incident_zip IN (11209, 11201, 11202);
    

    【讨论】:

    • 谢谢!这正是我所需要的! +1
    【解决方案2】:

    使用方括号 () 对 OR 进行分组:

    select COUNT(*) from complaints
    where created_date::date >= '2013-10-03' AND created_date::date <= '2014-05-31'
    AND (incident_zip = 11209 OR incident_zip = 11201 OR incident_zip = 11202);
    

    根据您的 SQL 语言,您可能能够编写:

    select COUNT(*) from complaints
    where created_date::date BETWEEN '2013-10-03' AND '2014-05-31'
    AND incident_zip IN (11209, 11201, 11202);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      • 2018-08-10
      • 1970-01-01
      • 2012-12-19
      • 2014-08-13
      • 2019-06-14
      相关资源
      最近更新 更多