简体   繁体   中英

SQL Server Between Start and End dates

在此处输入图片说明

I'm creating an internal holiday booking system and I need to put business logic rules into place but I need to do a check on how many people are booked off on the dates between the Start and End date because for example 2 apprentices may only be booked off on 1 day but I have no way off grabbing the dates between.

Any help would be appreciated

Below is the job role table

JobRoleTable

You haven't posted the RDBMS, or the names of the tables, or what exactly the Job Role table is supposed to be doing ... but I'll take a shot at this anyway. I'm using a recursive CTE to generate a list of dates, but it would be far better for you to use a Date table, and I don't even know whether your RDBMS will support this. I've also posted the syntax for a table variable below that populates data mimicking your sample.

The final output, naturally, will need to be customized to do whatever you need to do. This does show you, however, a list of every date when more than one employee is on vacation. Add extra conditions to the second JOIN or to the WHERE clause to filter on other things (like JobRole) if necessary.

-- 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM