简体   繁体   中英

Finding a gap in dates

I have a table with 3 columns:

Date smalldatetime not null
Val1 decimal not null
Val2 decimal not null

And a lot of data in this table. Not all calendar dates are presented in the table. How can I find all places where the dates gap is more than x days?

Here is how you can do this:

DECLARE @t TABLE
    (
      Date SMALLDATETIME NOT NULL ,
      Val1 DECIMAL NOT NULL ,
      Val2 DECIMAL NOT NULL
    )

INSERT INTO @t VALUES
('20150101', 1, 1),
('20150104', 1, 1),
('20150109', 1, 1),
('20150201', 1, 1),
('20150305', 1, 1),
('20150506', 1, 1)


;WITH cte AS(SELECT *, ROW_NUMBER() OVER(ORDER BY Date) AS Rn FROM @t)
SELECT c2.*, c1.Date AS PrevDate FROM cte c1
JOIN cte c2 ON c1.Rn = c2.Rn - 1
WHERE DATEDIFF(d, c1.Date, c2.Date) > 30 --this is your X

Output:

Date                Val1    Val2    Rn  PrevDate
2015-03-05 00:00:00 1       1       5   2015-02-01 00:00:00
2015-05-06 00:00:00 1       1       6   2015-03-05 00:00:00

You can create a date table in SQL Server database and use SQL date table to find gaps in date

Dates table is the reference table where all possible dates are included. You will compare the target table with dates table joining on date columns and listing the missing ones

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-2024 STACKOOM.COM