Robert Lewkovich Robert Lewkovich - 1 year ago 30
SQL Question

re creating SELECT that may require IN

Given a table with the following two columns
1) Date, DATE
2) Weather, INTEGER (0=ClearDay, 1=Rain, 2=Snow)

I’d like a SELECT that returns ALL dates when it rained AND snowed within -+ (N,M) days from the day it rained. I.e., if (-+)N,M=1,2 and it rained today (Wed) I’d want today’s date returned if it snowed on any day from Tue to Fri included, assuming only one weather value per day.


  • Example 1:

  • 1/1/2011, 0

  • 1/1/2011, 0

  • 1/2/2011, 2

  • 1/3/2011, 1

  • 1/4/2011, 1

  • 1/5/2011, 0

  • 1/6/2011, 0



With (-+)N,M=2,1 - return 1/3, 1/4


  • Example 2:

  • 1/1/2011, 0

  • 1/2/2011, 2

  • 1/3/2011, 1

  • 1/4/2011, 1

  • 1/5/2011, 1

  • 1/6/2011, 0

  • 1/7/2011, 2



With (-+)N,M=1,2, return 1/3, 1/5

Answer Source

This query should do it for you. Replace @N with the number of days before and @M with the number of days after to check. Note that I assume your table's name is t.

SELECT DISTINCT rain.date
FROM t AS rain
JOIN t AS snow ON snow.date between rain.date - @N AND rain.date + @M 
    AND snow.weather = 2
WHERE rain.weather = 1

I'm having trouble deciding what the correct way is to compare the dates in sqlite. I've tried looking it up but I'm getting conflicting advice. This sqlite doc page made it sound like julianday was the best way to compare just the DAY part of a DATE. If the above query doesn't work for you, try this version instead which uses julianday to get just the DAY component of the date.

SELECT DISTINCT rain.date
FROM t AS rain
JOIN t AS snow ON julianday(snow.date) between julianday(rain.date) - @N AND julianday(rain.date) + @M 
    AND snow.weather = 2
WHERE rain.weather = 1
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download