T-SQL:30 天间隔后的最新事件
我需要查找最近 30 天或更长时间没有发生事件之后发生的所有事件。我当前的查询仅找到第一个 30 天的间隔。如果没有 30 天或更长的间隔,则我使用默认日期返回所有行。
我还应该小心,如果事件早于 30 天,则不要返回该事件的单个实例。
鉴于以下事件,最近 30 天间隔后的最近事件应该是 6/30/2011,但我的查询返回 4/13/2011
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
)
I need to find all the events occurring after the most recent gap of 30 days or more without an event. My current query only finds the first gap of 30 days. If there aren't any gaps of 30 days or more then I use a default date to return all the rows.
I should also be careful not to return a single instance of an event if that event is older that 30 days.
Given the following events, the most recent event after most recent 30 day gap should be 6/30/2011, but my query returns 4/13/2011
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
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
Try this:
专为您的 sql 而设计。修正了一个误会
Made to fit your sql. Fixed a misunderstanding