我正在尝试按照创建它们的日期范围计算数据库中的行数,以及它们是否是多个邮政编码之一。在语义上,我想说的是在这段时间内计算这些邮政编码的所有投诉。我的查询看起来像这样,
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列吗?
答案 0 :(得分:1)
使用方括号()对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);
答案 1 :(得分: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);