间隔日期之间的查询

时间:2016-12-29 07:02:55

标签: mysql sql date intersect

我有下表。

enter image description here

我正在尝试获取与任何日期相交的记录,例如,如果我需要2002-12-29和2002-12-30之间的百分比,我应该获得第一条记录,其中包含28.60,我写了一个查询但有时我得到一些记录,但有时候我什么也得不到。任何帮助都会很棒。

这是查询

SELECT *
FROM myTable
WHERE ((fec_inicio < '2002-12-29'
AND fec_fin        > '2002-12-29')
OR (fec_inicio     < '2002-12-30'
AND fec_fin        > '2002-12-30'))

1 个答案:

答案 0 :(得分:0)

听起来你正在寻找SQL overlaps运算符,我认为MySQL并不支持。 overlaps运算符定义为

row_constructor overlaps  row_constructor

并且行构造函数的格式为

(Ls, Le) OVERLAPS (Rs, Re)

其中 Ls 表示左手开始 Le 表示左手

overlaps运算符被定义为在语义上等效于此表达式。

(Ls > Rs and (Ls < Re or Le < Re) ) or
(Rs > Ls and (Rs < Le or Re < Le) ) or
(Ls = Rs and Le is not null and Re is not null)

代替你的价值观给我这样的东西。 (未经测试)

select *
from myTable
where ( '2002-12-29' > fec_inicio and ('2002-12-29' < fec_fin or '2002-12-30' < fec_fin) ) or
      ( fec_inicio > '2002-12-29' and (fec_inicio < '2002-12-30' or fec_fin < '2002-12-30') ) or
      ( '2002-12-29' = fec_inicio and '2002-12-30' is not null and fec_fin is not null);

我希望我有正确的替换。 (我们知道希望并不能很好地扩展。)

从您的问题中不清楚您需要对重叠多行的范围做什么。但是,例如,它应该足够简单,从上面的查询中选择最小日期,并在该日期inner join获得完整的行。

说了这么多,你选择百分比的逻辑似乎很奇怪。试一下。

相关问题