如何按ID查找缺少的日期

时间:2015-12-29 22:21:21

标签: sql-server tsql

我需要帮助修改脚本,以便在给定的时间范围内按ID找到丢失的RevenuePeriod。我找到了一个类似的脚本,找到了给定ID的缺失日期,但我不知道如何修改脚本,它会给每个ID丢失的日期。

create table #WorksheetHistory (WorksheetID [int] IDENTITY(1,1) ,ID varchar(6), RevenuePeriod datetime)
insert into #WorksheetHistory (ID,RevenuePeriod) 

SELECT '000001','2015-06-01 00:00:00.00' Union All
SELECT '000001','2015-07-01 00:00:00.00' Union All
SELECT '000001','2015-11-01 00:00:00.00' Union All
SELECT '000001','2015-12-01 00:00:00.00' Union All
SELECT '000002','2015-06-01 00:00:00.00' Union All
SELECT '000002','2015-12-01 00:00:00.00'

DECLARE @EndDate datetime
DECLARE @StartDate datetime

SET @StartDate  = '2015-06-01 00:00:00.00'
SET @EndDate    = '2015-12-01 00:00:00.00'

;WITH Dates as
(
SELECT @StartDate AS dt
    UNION ALL
SELECT DATEADD(month, 1, dt) as dt
    FROM Dates
    WHERE dt < (select dateadd(month,-1,@EndDate)  enddate)
)

select Month(dt) as dtMonth, Year(dt) dtYear
from Dates d left outer join #WorksheetHistory w
on dateadd(month, datediff(month,0,d.dt),0)  = dateadd(month, datediff(month,0,w.RevenuePeriod),0) Where RevenuePeriod is null

Drop Table #WorksheetHistory

当前输出返回以下输出。我在脚本中意识到它没有返回ID,但即使我这样做,它也会返回null值,因为脚本指示返回null日期。我不知道如何将相关ID放入其中。

dt
2015-08-01 00:00:00.000
2015-09-01 00:00:00.000
2015-10-01 00:00:00.000

我想要的结果是返回遗失的ID以及各自缺失的日期。

ID      dt
000001  2015-08-01 00:00:00.00
000001  2015-09-01 00:00:00.00
000001  2015-10-01 00:00:00.00
000002  2015-07-01 00:00:00.00
000002  2015-08-01 00:00:00.00
000002  2015-09-01 00:00:00.00
000002  2015-10-01 00:00:00.00
000002  2015-11-01 00:00:00.00

1 个答案:

答案 0 :(得分:1)

使用EXCEPT:

WITH Dates as
(
    SELECT @StartDate AS dt
    UNION ALL
    SELECT DATEADD(month, 1, dt) as dt
    FROM Dates
    WHERE dt < DATEADD(m, -1, @EndDate)
)
-- all the possible combinations
SELECT w.ID, d.dt
FROM Dates d
CROSS JOIN (
    SELECT ID
        FROM #WorksheetHistory
        GROUP BY ID
) w
EXCEPT
-- the combinations you actually have
SELECT w.ID, d.dt
FROM Dates d
JOIN #WorksheetHistory w
    ON d.dt = w.RevenuePeriod;