我简要解释问题。
select distinct DATE from #Table where DATE >='2016-01-01'
输出:
Date
2016-11-23
2016-11-22
2016-11-21
2016-11-19
2016-11-18
现在我需要找出缺少的日期与我们的年度' 2016'
的日历比较即。这里约会' 2016-11-20 '不见了。
我想要缺少日期列表。
感谢您阅读本文。祝你有美好的一天。
答案 0 :(得分:2)
你需要生成日期,你必须找到遗漏的日期。下面用递归cte我已经完成了
;WITH CTE AS
(
SELECT CONVERT(DATE,'2016-01-01') AS DATE1
UNION ALL
SELECT DATEADD(DD,1,DATE1) FROM CTE WHERE DATE1<'2016-12-31'
)
SELECT DATE1 MISSING_ONE FROM CTE
EXCEPT
SELECT * FROM #TABLE1
option(maxrecursion 0)
答案 1 :(得分:1)
您需要生成日期,然后找到遗漏的日期。递归CTE是生成少数日期的一种方法。另一种方法是使用master..spt_values
作为数字列表:
with n as (
select row_number() over (order by (select null)) - 1 as n
from master..spt_values
),
d as (
select dateadd(day, n.n, cast('2016-01-01' as date)) as dte
from n
where n <= 365
)
select d.date
from d left join
#table t
on d.dte = t.date
where t.date is null;
如果您对缺少日期的范围感到满意,则根本不需要日期列表:
select date, (datediff(day, date, next_date) - 1) as num_missing
from (select t.*, lead(t.date) over (order by t.date) as next_date
from #table t
where t.date >= '2016-01-01'
) t
where next_date <> dateadd(day, 1, date);
答案 2 :(得分:1)
使用CTE
并获取CTE
表中的所有日期,然后与您的表格进行比较。
CREATE TABLE #yourTable(_Values DATE)
INSERT INTO #yourTable(_Values)
SELECT '2016-11-23' UNION ALL
SELECT '2016-11-22' UNION ALL
SELECT '2016-11-21' UNION ALL
SELECT '2016-11-19' UNION ALL
SELECT '2016-11-18'
DECLARE @DATE DATE = '2016-11-01'
;WITH CTEYear (_Date) AS
(
SELECT @DATE
UNION ALL
SELECT DATEADD(DAY,1,_Date)
FROM CTEYear
WHERE _Date < EOMONTH(@DATE,0)
)
SELECT * FROM CTEYear
WHERE NOT EXISTS(SELECT 1 FROM #yourTable WHERE _Date = _Values)
OPTION(maxrecursion 0)