我们正在为员工休假制作日期范围选择器
例如我将以2016年1月的用户为例,我们的系统从星期日到星期六
如果员工从1月14日到20日休假,他们应该在10-16和17-23之间的日期
我只是想不出如何编写一个sql查询,将其限制为这两个日期。
我拥有的是:
DECLARE @WeekRangeStart DATETIME ='2016/01/10';
DECLARE @WeekRangeEnd DATETIME = '2016/01/16';
SELECT [ID],
[EmpName],
[EmpType]
FROM Vacations
WHERE VacationStartDate >= @WeekRangeStart OR VacationEndDate >= @WeekRangeStart
--OUTPUT
--ALL DAYS BEFORE THIS WOULD BE TRUE...
--1/14/2016 >= 1/10/2016 TRUE
--1/20/2016 >= 1/10/2016 TRUE
-- NEXT WEEK
--1/14/2016 >= 1/17/2016 FALSE
--1/20/2016 >= 1/17/2016 TRUE
-- NEXT WEEK
--1/14/2016 >= 1/24/2016 FALSE
--1/20/2016 >= 1/24/2016 FALSE
--ALL DAYS AFTER THIS DAY WOULD BE FALSE...
但是这只适用于已经过去的事情,但是如果我要在3月份预订一天,我会一直在时间表上显示,因为我的开始时间比今天更大。我该如何将其限制在该范围内?
答案 0 :(得分:0)
DECLARE @WeekRangeStart DATETIME ='2016/01/10';
DECLARE @WeekRangeEnd DATETIME = '2016/01/16';
SELECT [ID],
[EmpName],
[EmpType]
FROM Vacations
WHERE VacationStartDate between @WeekRangeStart and @WeekRangeEnd
or VacationEndDate Between @WeekRangeStart and @WeekRangeEnd
答案 1 :(得分:0)
这可能很有用。使用递归CTE我得到假期跨越的所有日期。然后根据提供的周范围返回它跨越的周数。
DECLARE @WeekRangeStart DATETIME ='2016/01/10';
DECLARE @WeekRangeEnd DATETIME = '2016/01/16';
DECLARE @VacationStartDate DATETIME = '2016-01-14'
DECLARE @VacationEndDate DATETIME = '2016-01-20'
;WITH cte AS
(
SELECT @VacationStartDate AS Dates
UNION ALL
SELECT DATEADD(dd, 1, dates)
FROM cte
WHERE dates < @VacationEndDate
)
SELECT DISTINCT
DATEADD(dd, -(DATEPART(dw, dates)-1), dates) AS WeekStartDate,
DATEADD(dd, 7-(DATEPART(dw, dates)), dates) AS WeekEndDate
FROM cte
WHERE dates BETWEEN @WeekRangeStart AND @WeekRangeEnd