给出一个包含以下两列的表 1)日期,日期 2)天气,INTEGER(0 = ClearDay,1 = Rain,2 = Snow)
我想要一个SELECT,它会在下雨之日返回所有日期 - 从下雨之日开始 - +(N,M)天。也就是说,如果( - +)N,M = 1,2并且今天(周三)下雨我想要在今天从周二到周五的任何一天下雪的情况下返回今天的日期,假设每天只有一个天气价值。
使用( - +)N,M = 2,1 - 返回1 / 3,1 / 4
使用( - +)N,M = 1,2,返回1 / 3,1 / 5
答案 0 :(得分:1)
此查询应该为您完成。将@N
替换为之前的天数,将@M
替换为检查后的天数。请注意,我假设您的表名为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
我无法确定比较sqlite中日期的正确方法。我已经尝试过了,但是我得到了相互矛盾的建议。 This sqlite doc page听起来像julianday
只是比较日期DAY部分的最佳方法。如果上述查询不适合您,请尝试使用此版本,而使用julianday
只获取日期的DAY组件。
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
答案 1 :(得分:0)
你可以通过做一个非等值连接来做到这一点。 (我在Oracle上做了这个,语法可能需要调整)
CREATE TABLE temp (
weather_date DATE,
weather NUMBER)
;
INSERT ALL
INTO temp (weather_date, weather) VALUES ('1-jan-2011', 0)
INTO temp (weather_date, weather) VALUES ('2-jan-2011', 2)
INTO temp (weather_date, weather) VALUES ('3-jan-2011', 1)
INTO temp (weather_date, weather) VALUES ('4-jan-2011', 1)
INTO temp (weather_date, weather) VALUES ('5-jan-2011', 0)
INTO temp (weather_date, weather) VALUES ('6-jan-2011', 0)
SELECT * from dual;
以下查询根据上述数据集返回所需的结果。根据需要在JOIN子句中更改offests。
SELECT
DISTINCT a.weather_date
FROM
temp a
JOIN temp b
ON b.weather_date BETWEEN a.weather_date - 2 AND a.weather_date + 1
WHERE
a.weather = 1
AND b.weather = 2;
答案 2 :(得分:0)
select distinct date
from table t
where exists (select 1
from table t2
where t.weather <> t2.weather
and julianday(t2.date) between julianday(t1.date - N)
and julianday(t1.date + M)
)
您需要将t1.date - N
和t1.date + M
替换为特定于您的rdbms的日期算术运算符。我认为这对SQLite来说是正确的......
答案 3 :(得分:0)
SELECT d FROM weather WHERE d IN (
SELECT date(d, '+1 day') FROM weather WHERE w=1
UNION
SELECT date(d, '+2 day') FROM weather WHERE w=1
) AND w IN (1, 2)