我需要在没有事件的情况下找到最近30天或更长时间间隔之后发生的所有事件。我当前的查询只发现30天的第一个差距。如果没有30天或更长的间隙,那么我使用默认日期返回所有行。
如果该事件超过30天,我还应该注意不要返回事件的单个实例。
鉴于以下事件,最近30天差距后的最新事件应为2011年6月30日,但我的查询将于2011年4月13日返回
EventDate EventType
========= =========
4/13/2011 1
5/20/2011 1
6/30/2011 1
DECLARE @DefaultDate DATETIME
SET @DefaultDate = '1/1/2011'
SELECT ISNULL(MAX(EventDate), @DefaultDate)
FROM Events e
WHERE
e.EventType = 1
AND NOT EXISTS (SELECT 1
FROM Events
WHERE EventType = 1
AND DATEDIFF(dd,EventDate, e.EventDate) ) > 30
)
答案 0 :(得分:1)
适合你的sql。修正了一个误解
SELECT COALESCE(t1.Eventdate, @DefaultDate) from event t1
RIGHT JOIN
(
SELECT max(EventDate) EventDate FROM event t
WHERE EventType = 1 AND
NOT EXISTS
(SELECT 1 FROM event WHERE EventType = 1 AND
t.eventdate <= eventdate + 30 and t.eventdate > eventdate)
AND EXISTS (SELECT 1 FROM event WHERE EventType = 1
AND t.eventdate > eventdate)) t2
on t1.eventdate >= t2.eventdate
答案 1 :(得分:1)
试试这个:
declare @t table(EventDate datetime)
insert @t(EventDate) values('4/13/2011'), ('5/20/2011'), ('6/30/2011'), ('7/1/2011')
select *
from @t
where EventDate >
(
select max(t1.EventDate)
from @t t1
join @t t2 ON t2.EventDate > t1.EventDate
and not exists (
select 1
from @t t3
where t3.EventDate < t2.EventDate and t3.EventDate > t1.EventDate
)
where datediff(day, t1.EventDate, t2.EventDate) > 30
)