我有一个包含多个合约的表,每个合约都有一个开始日期和结束日期,如下所示:
| ID | Contract Name | Start Date | End Date |
|-------|-------------------|--------------|------------|
| 1 | Joe Bloggs | 2012-01-01 | 2012-02-05 |
| 2 | John Smiths | 2012-02-01 | 2012-02-20 |
| 3 | Johnny Briggs | 2012-03-01 | 2012-03-20 |
我要做的是构建一个查询,以检索在特定时间段内处于活动状态的合同。因此,如果我的开始日期为2012-02-10
且结束日期为2012-03-21
,则应显示以下合同:
| ID | Contract Name | Start Date | End Date |
|-------|-------------------|--------------|------------|
| 2 | John Smiths | 2012-02-01 | 2012-02-20 |
| 3 | Johnny Briggs | 2012-03-01 | 2012-03-20 |
我的问题是,我不知道如何构建查询来执行此操作。这是我到目前为止所得到的:
SELECT *
FROM contracts c
WHERE c.startdate BETWEEN '2012-02-10'
AND '2012-03-21'
AND c.enddate BETWEEN '2012-02-10'
AND '2012-03-21'
但这不起作用,不会检索任何记录。我做错了什么?
答案 0 :(得分:3)
呃,时间是线性的吗?
SELECT *
FROM contracts
WHERE end_date >= '2012-02-10'
AND start_date <= '2012-03-21';
让我举例说明......
A-------------B
<------->
<------>
<----------->
<---------------------->
在上述所有情况下,开始日期都小于B.结束日期大于A.
答案 1 :(得分:3)
SELECT * FROM contracts
WHERE (START_DATE between '2012-03-01' AND '2013-03-21')
OR (END_DATE between '2012-03-01' AND '2013-03-21')
OR (START_DATE<= '2012-03-01' AND END_DATE >='2013-03-21');
答案 2 :(得分:0)
对我来说,一个好的要求将是
SELECT * FROM contracts c WHERE c.startdate >'2012-02-10' AND c.enddate < '2012-03-21'
答案 3 :(得分:0)
应该是这样的
SELECT *
FROM contracts c
WHERE c.startdate >= '2012-02-10'
AND c.enddate <= '2012-03-21'
答案 4 :(得分:0)
SELECT * FROM contracts
WHERE
(START_DATE between '2012-03-01' AND '2013-03-21')
OR (END_DATE between '2012-03-01' AND '2013-03-21')
OR (START_DATE<= '2012-03-01' AND END_DATE >='2013-03-21');
说明:
(START_DATE between '2012-03-01' AND '2013-03-21')
:从输入日期开始的间隔记录。可能包括间隔的第一部分或全部。
(END_DATE between '2012-03-01' AND '2013-03-21')
:输入日期之间的间隔。可能包括间隔的最后一部分或全部。
(START_DATE<= '2012-03-01' AND END_DATE >='2013-03-21')
:输入日期仅包含在一个时间间隔内