过滤SQL Server中的连续日期

时间:2017-03-15 20:28:41

标签: sql-server sql-server-2008 tsql

如果连续日期是昨天,我想从我的假期表中过滤连续日期。下面是我的代码,用于获取行号的连续日期。

SELECT 
    RW = ROW_NUMBER() OVER( PARTITION BY GRP ORDER BY HolidayDate),
    HolidayDate
FROM
    (SELECT 
         HolidayDate, 
         DATEDIFF(Day, '1900-01-01', HolidayDate) - ROW_NUMBER() OVER (ORDER BY HolidayDate) AS GRP, 
         HolidayType
     FROM 
         Holiday) A
ORDER BY
    HolidayDate 

例如,昨天的日期是2017年3月14日。如果涉及此日期的任何连续假期,我需要从Holiday表中获取数据。

如果没有匹配则输出应为null,否则它应显示如下日期

03/12/2017
03/13/2017
03/14/2017

1 个答案:

答案 0 :(得分:2)

嗯,你快到了!

定义"昨天"作为参数,因为它很容易找到。

CREATE TABLE Holiday(
    HolidayDate SMALLDATETIME PRIMARY KEY, 
    HolidayType VARCHAR(20)
);

INSERT INTO Holiday VALUES 
  ('2016-12-25', 'A'), ('2016-12-26', 'A'), ('2017-01-01', 'A'), 
  ('2017-04-12', 'A'), ('2017-04-13', 'A'), ('2017-04-14', 'A');

DECLARE @yesterday SMALLDATETIME;
SET @yesterday = '2017-04-13'; -- belongs to a group of consecutive holidays
-- SET @yesterday = '2017-01-01'; -- isolated holiday
-- SET @yesterday = '2017-02-10'; -- not a holiday

; WITH groups as 
(
SELECT 
    HolidayDate, 
    DATEDIFF(Day, '1900-01-01', HolidayDate) 
    - ROW_NUMBER() OVER (ORDER BY HolidayDate) AS GRP, 
    HolidayType
FROM Holiday
),
consecutive as (
    SELECT GRP FROM groups GROUP BY GRP HAVING COUNT(*) > 1
)
SELECT DISTINCT g2.HolidayDate, g2.HolidayType 
FROM consecutive c 
JOIN groups g1 ON c.GRP = g1.GRP 
JOIN groups g2 ON g1.GRP = g2.GRP
WHERE g1.HolidayDate = @yesterday;