生成缺少的日期+ SQL服务器(基于集)
id eventid startdate enddate
1 1 2009-01-03 2009-01-05
1 2 2009-01-05 2009-01-09
1 3 2009-01-12 2009-01-15
如何生成属于每一个事件ID丢失的日期?
编辑: 缺失的差距是基于eventid的找出。例如对于事件类型1,输出应该是1/3/2009,1/4/2009,1/5/2009 ..对于事件类型ID 2,它将是1/5/2009,1/6/2009 ...到1/9/2009等
我的任务是找出两个给定日期之间的缺失日期。
这里是我迄今所做的全部事情
declare @tblRegistration table(id int primary key,startdate date,enddate date)
insert into @tblRegistration
select 1,'1/1/2009','1/15/2009'
declare @tblEvent table(id int,eventid int primary key,startdate date,enddate date)
insert into @tblEvent
select 1,1,'1/3/2009','1/5/2009' union all
select 1,2,'1/5/2009','1/9/2009' union all
select 1,3,'1/12/2009','1/15/2009'
;with generateCalender_cte as
(
select cast((select startdate from @tblRegistration where id = 1)as datetime) DateValue
union all
select DateValue + 1
from generateCalender_cte
where DateValue + 1 <= (select enddate from @tblRegistration where id = 1)
)
select DateValue as missingdates from generateCalender_cte
where DateValue not between '1/3/2009' and '1/5/2009'
and DateValue not between '1/5/2009' and '1/9/2009'
and DateValue not between '1/12/2009'and'1/15/2009'
其实什么,我试图做的是,我已经产生了压延机台,并从那里我试图找出缺少的日期根据id的
理想的输出将是
eventid missingdates
1 2009-01-01 00:00:00.000
1 2009-01-02 00:00:00.000
3 2009-01-10 00:00:00.000
3 2009-01-11 00:00:00.000
而且它必须是基于SET和开始和结束日期不应该被硬编码
感谢adavnce
下使用递归CTE(SQL服务器2005 +):
WITH dates AS (
SELECT CAST('2009-01-01' AS DATETIME) 'date'
UNION ALL
SELECT DATEADD(dd, 1, t.date)
FROM dates t
WHERE DATEADD(dd, 1, t.date) <= '2009-02-01')
SELECT t.eventid, d.date
FROM dates d
JOIN TABLE t ON d.date BETWEEN t.startdate AND t.enddate
它生成使用DATEADD功能日期。它可以被改变,以开始&结束日期作为参数。根据KM's comments,它比使用数字表格技巧更快。
先生,这会给我1个事件类型。对于所有事件类型如何? – 2009-11-02 06:13:09
事件类型?对不起,但我不明白你指的是什么。 – 2009-11-02 06:20:06
对不起。可能我没有让自己清楚..实际上缺失的差距是基于eventid的发现。例如对于事件类型1,输出应该是1/3/2009,1/4/2009,1/5/2009 ..对于事件类型ID 2,它将是1/5/2009,1/6/2009 ...到1/9/2009等 – 2009-11-02 06:23:38
就像rexem - 我做了一个包含类似CTE的函数来生成任何需要的日期时间间隔序列。按照日期时间间隔汇总数据非常方便,就像您正在做的那样。 更详细的岗位和功能的源代码在这里:
Insert Dates in the return from a query where there is none
一旦你拥有了“按日期的事件计数” ......你缺少的日期应该是一个有0
计数的那些+1优秀的东西! – 2009-11-02 06:38:20
“缺失日期”是什么意思? – 2009-11-02 05:50:03
我正在使用sql server 2005. – 2009-11-02 05:54:39