SQL Server在开始日期和结束日期之间

时间:2014-08-11 08:04:18

标签: sql sql-server

enter image description here

我正在创建一个内部假日预订系统,我需要制定业务逻辑规则,但我需要检查在开始日期和结束日期之间预订了多少人,例如2名学徒只能在1天内预订,但我无法抓住他们之间的日期。

任何帮助将不胜感激

以下是工作角色表

JobRoleTable

1 个答案:

答案 0 :(得分:0)

您还没有发布RDBMS,或者表格的名称,或者作业角色表应该做什么......但是我还是会对此进行拍摄。我使用递归CTE生成日期列表,但是使用Date表会好得多,而且我甚至不知道你的RDBMS是否支持这个。我还在下面发布了一个表变量的语法,用于填充模拟样本的数据。

当然,最终输出需要定制,以完成您需要做的任何事情。但是,这确实向您显示了多个员工休假时的每个日期列表。在第二个JOINWHERE子句中添加额外条件,以便在必要时过滤其他内容(如JobRole)。

-- Code originally from http://smehrozalam.wordpress.com/2009/06/09/t-sql-using-common-table-expressions-cte-to-generate-sequences/

-- Define start and end limits
DECLARE @todate DATETIME, @fromdate DATETIME
SELECT @fromdate='2014-01-01', @todate=GETDATE()-1

DECLARE @TimeOff TABLE (StartDate DATETIME, EndDate DATETIME, EmployeeID INT)

INSERT INTO @TimeOff (StartDate, EndDate, EmployeeID)
SELECT '1/1/2014', '1/7/2014', 7 UNION 
SELECT '2/1/2014', '2/7/2014', 7 UNION 
SELECT '3/3/2014', '3/9/2014', 7 UNION 
SELECT '2/5/2014', '2/6/2014', 8 

;WITH DateSequence( Date ) AS -- this will list all dates.  Use this if you don't have a date table
  (
    SELECT @fromdate as Date
    UNION ALL 
    SELECT DATEADD(DAY, 1, Date)
    FROM DateSequence
    WHERE Date < @todate
  )

--select result
SELECT DateSequence.Date, TimeOffA.StartDate, TimeOffB.EndDate, TimeOffA.EmployeeID
FROM 
    DateSequence -- a full list of all possible dates
     INNER JOIN 
    @TimeOff TimeOffA ON -- all dates when an employee is on vacation -- replace this with your actual table's name
        DateSequence.Date BETWEEN TimeOffA.StartDate AND TimeOffA.EndDate
     INNER JOIN 
    @TimeOff TimeOffB ON -- all dates when an employee who is NOT employee A is on vacation -- replace this with your actual table's name
        DateSequence.Date BETWEEN TimeOffB.StartDate AND TimeOffB.EndDate AND
        TimeOffA.EmployeeID <> TimeOffB.EmployeeID
option (MaxRecursion 2000)