简体   繁体   中英

Counting rows in SQL with multiple AND & OR statements

I'm trying to count the number of rows in a database by a date range in which they were created and by if they are one of several zip codes. Semantically what I'm trying to say is count all the complaints from these zip codes during this period of time. My query looks like this,

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;

I can't seem to get the query to run without the OR statement making the AND statements meaningless. Could someone explain how to group it so the OR statement only affects the incident_zip column and not the created_date column?

Use brackets () to group the ORs:

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);

Depending on your SQL language you might be able to write:

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

In this case there's no need for multiple clauses containing incident_zip . Instead, group them together using an IN clause:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM