我想找到两个日期之间缺少的日期。 表格中存在一个名为date的字段
2018-11-13、2018-11-18、2018-11-20、2018-11-25
我想要从2018-11-13到2018-11-25的丢失日期
Expected Output
2018-11-14
2018-11-15
2018-11-16
2018-11-17
2018-11-19
2018-11-21
2018-11-22
2018-11-23
2018-11-24
答案 0 :(得分:0)
您可以在下面使用递归CTE-
DECLARE @s_date date = '2018-11-13',
@e_date date = '2018-12-01'
;WITH cte AS (
SELECT @s_date as fdate
UNION ALL
SELECT CAST(DATEADD(day,1,fdate) as date)
FROM cte
WHERE date_ < @e_date
)
SELECT * FROM cte eft join yourtablename t2 on t1.Date=t2.date
where t2.date is null
OPTION (MAXRECURSION 0)
或者您可以使用日历表
DECLARE @s_date date = '2018-11-13',
@e_date date = '2018-12-01'
SELECT Date
FROM dbo.Calendar t1 left join yourtablename t2 on t1.Date=t2.date
and Date >= @s_date AND Date < @e_date
where t2.date is null
答案 1 :(得分:0)
这肯定会起作用:
select * from date_ranges;
13-NOV-18
01-DEC-18
16-NOV-18
20-NOV-18
set serveroutput on;
create or replace procedure date_range( d1 date, d2 date) is
op date;
op2 date;
diff number;
comp date;
a number;
b number;
j number;
cursor c1 is select a from date_ranges;
begin
select d2-d1 into diff from dual;
for op in 1..diff
loop <<forloop>>
j:=0;
select d1+op into op2 from dual;
open c1;
loop <<curloop>>
fetch c1 into comp;
if(c1%notfound) then
exit;
end if;
select sysdate-to_date(comp) into a from dual;
select sysdate-to_date(op2) into b from dual;
if(a=b)then
j:=1;
end if;
end loop curloop;
close c1;
if(j=0)then
DBMS_OUTPUT.PUT_LINE(op2);
end if;
end loop forloop;
end;
/
declare
m date;
n date;
begin
select min(a) into m from date_ranges;
select max(a) into n from date_ranges;
date_range(m,n);
end;
/
输出:
14-NOV-18
15-NOV-18
17-NOV-18
18-NOV-18
19-NOV-18
21-NOV-18
22-NOV-18
23-NOV-18
24-NOV-18
25-NOV-18
26-NOV-18
27-NOV-18
28-NOV-18
29-NOV-18
30-NOV-18
因此日期16 nov和20 nov不会被打印,因为它们存在于查询表中,而缺失日期则显示在采样日期的最小值和最大值之间。 谢谢!!!!!!!!!!!!!!!!!! 1
答案 2 :(得分:-1)
如果您想将丢失的日期存储在某些表中,则可以使用While循环。这样也可以工作。
Declare @mindate date ='2018-11-13'
Declare @maxdate date = '2018-12-01'
select '2018-11-18' as Existingdate into #tmp --made existing dates
create table Missingdates (Missingdate date)
Declare @id int = 1
While dateadd(day, @id, @mindate) > @mindate and dateadd(day, @id, @mindate) < @maxdate
Begin
insert into Missingdates select dateadd(day, @id, @mindate) as MIssingDate where not exists (Select * from #tmp t where t.Existingdate = dateadd(day, @id, @mindate))
set @id = @id+1
end
select * from Missingdates
输出:
Missingdate
2018-11-14
2018-11-15
2018-11-16
2018-11-17
2018-11-19
-- so on
添加了不存在子句,并且不会提供现有日期。