我需要一个SQL查询来检索包含在选定时间段内的数据,时间段是用户从日历中选择的字符串。
例如,如果用户选择时间段'2012-07-01'到'2012-07-04',我有以下表< /强>:
ID || start_date || end_date
1 || 2012-07-02 || 2012-07-04
2 || 2012-07-06 || 2012-08-05
3 || 2012-07-01 || 2012-09-01
4 || 2012-06-25 || 2012-09-01
如果像这样写一个sql 查询:
SELECT ID, start_date, end_date
FROM TABLE
WHERE start_date BETWEEN '2012-07-01' AND '2012-07-04'
此返回从“2012-07-01”开始到“2012-07-04”的所有行
ID || start_date || end_date
1 || 2012-07-02 || 2012-07-04
3 || 2012-07-01 || 2012-09-01
但是,我想要此期间包含的所有数据,因此结果必须为:
ID || start_date || end_date
1 || 2012-07-02 || 2012-07-04
3 || 2012-07-01 || 2012-09-01
4 || 2012-06-25 || 2012-09-01
ID为4的行我也希望在结果中,因为用户选择的时间段在start_date和end_date之下。
答案 0 :(得分:1)
我认为这就是你要找的东西:
SELECT ID, start_date, end_date
FROM TABLE
WHERE start_date <= '2012-07-01' AND
end_date >= '2012-07-04';
答案 1 :(得分:1)
您必须涵盖三种类型的事件:
所以你应该使用它:
SELECT ID, start_date, end_date
FROM your_table
WHERE (start_date BETWEEN '2012-07-01' AND '2012-07-04')
OR (end_date BETWEEN '2012-07-01' AND '2012-07-04')
OR (start_date <= '2012-07-01' AND
end_date >= '2012-07-04')
快速概述:
Interval: S---------E
Case 1 : ---| : : NOT WANTED
Case 2 : ----------:----| : WANTED
Case 3 : ----------:---------:------ WANTED - YOUR PROBLEM
Case 4 : |------:----| : WANTED
Case 5 : |------:---------:------ WANTED
Case 6 : : |---| : WANTED
Case 7 : : |------:------ WANTED
Case 8 : : : |--- NOT WANTED
您遇到问题的情况就是案例3.将通过添加额外条件start_date <= '2012-07-01' AND end_date >= '2012-07-04'
来解决。
答案 2 :(得分:1)
SELECT ID, start_date, end_date
FROM TABLE
WHERE start_date BETWEEN '2012-07-01' AND '2012-07-04'
您只能按开始日期选择,您可以通过以下方式询问:
(start_date between begin, end) OR
(end_date between begin, end) OR
(start_date <= begin AND end_date >= end)
这样:
(start_date between begin, end )
:您拥有从
(end_date between begin, end)
:您拥有在范围内完成的所有活动
(start_date <= begin AND end_date >= end)
:您拥有范围