我需要在两个日期(7-01-14和6-30-15)之间找到成员资格,这两个日期在该时间范围内已经成为至少4个月或更长时间的成员。有一个START_DATE和END_DATE列。任何意见,将不胜感激。谢谢。
答案 0 :(得分:1)
这适用于sqlserver 2012.如果您使用的是早期版本,则可以替换where子句:
DECLARE @t table(START_DATE date, END_DATE date)
INSERT @t values
('2015-01-01','2015-08-30'),('2015-01-01','2015-12-30'),
('2015-08-01','2015-12-30'),('2015-11-01','2017-12-30'),
('2016-01-01','2017-12-30'),('2017-01-01','2017-12-30')
DECLARE @from date='2015-7-01'
DECLARE @to date='2016-03-01'
SELECT *
FROM @t
WHERE
DATEADD(month,4, IIF(@from<START_DATE, START_DATE, @FROM)) <=
IIF(@to>END_DATE, END_DATE, @to)
/*
--this is for sqlserver 2008
DATEADD(month,4, CASE WHEN @from<START_DATE THEN START_DATE ELSE @FROM END) <=
CASE WHEN @to>END_DATE THEN END_DATE ELSE @to END
*/
答案 1 :(得分:0)
您可以使用此代码:
select *
from YourTable
where DateColumn between '2014/01/7' and '2006/05/30' and
start_date >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -4, current_timestamp)), 0)
答案 2 :(得分:0)
让我们调用您的表格注册。
首先..我们希望所有在7-01-14
和6-30-15
之间注册的人
Select *
From Enrollment
Where Start_Date Between '7-01-14' and '6-30-15'
And End_Date Between '7-01-14' and '6-30-15'
此外,在该时间段内,成员资格必须至少持续数月。
Select *
From Enrollment
Where Start_Date Between '7-01-14' and '6-30-15'
And End_Date Between '7-01-14' and '6-30-15'
And DateDiff (month, Start_Date, End_Date) > 4
但请考虑以下情况:
在这种情况下,您必须对查询进行适当的更改,以便在需要时处理这些情况。
例如,如果Start_Date OR End_Date可以在指定的截止日期之间,但成员资格仍需要4个月
Select *
From Enrollment
Where
(
Start_Date Between '7-01-14' and '6-30-15'
OR End_Date Between '7-01-14' and '6-30-15'
)
And DateDiff (month, Start_Date, End_Date) >= 4
但是,如果Start_Date小于cutff的开头,并且End_Date大于截止的结束,并且成员资格仍需要4个月,那该怎么办
Select *
From Enrollment
Where
(
(Start_Date Between '7-01-14' and '6-30-15' OR End_Date Between '7-01-14' and '6-30-15')
OR
(Start_Date < '7-01-14' and End_Date > '6-30-15')
)
And DateDiff (month, Start_Date, End_Date) >= 4