2013-12-11 43 views
2

记录进行建设和基于Display next event date重复事件系统的SQL Fiddle忽略了日期范围

它运作良好。我尝试将叶子计划与calander中的重复事件进行集成来过滤它。意味着如果他们属于计划假期,我需要忽略重复事件。

这里是我的离去,详细架构

CREATE TABLE dbo.Doctor 
(
    DoctorID TINYINT IDENTITY(1, 1) NOT NULL, 
    DoctorName VARCHAR(10) NOT NULL, 
    CONSTRAINT PK_Doctor_DoctorID PRIMARY KEY (DoctorID) 
) 


INSERT Doctor(DoctorName) VALUES ('Dr John') 

CREATE TABLE dbo.Leaves 
(  LeaveID INT IDENTITY(1, 1) NOT NULL, 
     DoctorID TINYINT NOT NULL, 
     LeaveStartDateTime DATETIME2 NOT NULL, 
     LeaveEndDateTime DATETIME2 NULL, 

    CONSTRAINT PK_Leaves_LeaveID PRIMARY KEY (LeaveID), 
    CONSTRAINT FK_Leaves_DoctorID FOREIGN KEY (DoctorID) REFERENCES dbo.Doctor (DoctorID) 

); 

Leave Data

  1. 起始日期 '20140115 00:00:00' 到 '20140116 11:59:59' - >15吨& 16日( 2天)

  2. 从日期'20140120 00:00:00'到'20140125 11:59:59' - > 20 - 25日(6天)

我需要删除其上面

查询

WITH RepeatingEvents AS 
( SELECT d.DoctorName, 
      l.LeaveStartDateTime, 
      l.LeaveEndDateTime, 
      e.Name, 
      re.StartDateTime, 
      re.EndDateTime, 
      re.TimesToRepeat, 
      RepeatEventDate = CAST(c.DateKey AS DATETIME) + CAST(re.StartTime AS DATETIME), 
      RepeatNumber = ROW_NUMBER() OVER(PARTITION BY re.RepeatEventID ORDER BY c.Datekey) 
    FROM dbo.Event e 
      INNER JOIN dbo.RepeatEvent re 
       ON e.EventID = re.EventID 
      INNER JOIN dbo.RepeatType rt 
       ON rt.RepeatTypeID = re.RepeatTypeID 
      INNER JOIN dbo.Calendar c 
       ON c.DateKey >= re.StartDate 
      INNER JOIN dbo.RepeatDayOfWeek rdw 
       ON rdw.RepeatEventID = re.RepeatEventID 
       AND rdw.DayNumberOfWeek = c.DayNumberOfWeek 
      INNER JOIN dbo.DoctorXEvent de ON e.EventID = de.EventID 
      INNER JOIN dbo.Doctor d ON d.DoctorID = de.DoctorID 
      LEFT JOIN dbo.Leaves l ON l.DoctorID = d.DoctorID 
    WHERE rt.Name = 'Weekly' 
) 
SELECT DoctorName, LeaveStartDateTime, LeaveEndDateTime,Name as EventName, StartDateTime, RepeatEventDate, RepeatNumber 
FROM RepeatingEvents 
WHERE (TimesToRepeat IS NULL OR RepeatNumber <= TimesToRepeat) 
AND  (EndDateTime IS NULL OR RepeatEventDate <= EndDateTime) 
AND  (RepeatEventDate NOT BETWEEN LeaveStartDateTime AND LeaveEndDateTime) 

SQL FIDDLE DEMO

提到的日期介于行

我的查询没有过滤这些记录并给出重复条目因为LEFT JOIN。

回答

1

由于日期不参与连接,因此左连接离开不起作用。 更换新谓词的左连接删除不需要的行:

AND NOT EXISTS 
    (SELECT 1 FROM Leaves l WHERE l.doctorId = d.doctorId 
    AND CAST(c.DateKey AS DATETIME) + CAST(re.StartTime AS DATETIME) 
    BETWEEN l.LeaveStartDateTime AND l.LeaveEndDateTime) 

这样不需要的行,重复的,将被删除。

/丹尼尔

+0

能否请您更新小提琴链接给我,给我这正与你的代码的新的链接? – Billa

+0

http://sqlfiddle.com/#!3/2b1a4/14/0 –

+0

有没有子查询的方法吗? – Billa