我正在尝试创建一个显示包含开始和结束时间的事件的视图。应该从仅具有事件时间字段和事件类型字段的现有表中收集此视图。
所以当前的EventTable看起来像这样:
EventTime | BooleanField
------------------------------
1/1/2010 6:00AM 1
1/2/2010 6:00AM 0
1/3/2010 6:00AM 1
1/4/2010 6:00AM 1
1/5/2010 6:00AM 0
结果集应如下所示
StartTime | EndTime
-----------------------------
1/1/2010 6:00AM 1/2/2010 6:00AM
1/3/2010 6:00AM 1/5/2010 6:00AM
因此视图应显示布尔字段为true的句点。
在SQL Server 2008中是否有一个简单的解决方案来实现这一目标?
谢谢你的帮助!
答案 0 :(得分:3)
您可以尝试类似(完整示例)
DECLARE @EventTable TABLE(
EventTime DATETIME,
BooleanField INT
)
INSERT INTO @EventTable (EventTime,BooleanField) SELECT '1/1/2010 6:00AM',1
INSERT INTO @EventTable (EventTime,BooleanField) SELECT '1/2/2010 6:00AM',0
INSERT INTO @EventTable (EventTime,BooleanField) SELECT '1/3/2010 6:00AM',1
INSERT INTO @EventTable (EventTime,BooleanField) SELECT '1/4/2010 6:00AM',1
INSERT INTO @EventTable (EventTime,BooleanField) SELECT '1/5/2010 6:00AM',0
;WITH Dates AS (
SELECT *,
(SELECT MIN(EventTime) FROM @EventTable WHERE EventTime > e.EventTime AND BooleanField = 0) EndDate
FROM @EventTable e
WHERE BooleanField = 1
)
SELECT MIN(EventTime) StartDate,
EndDate
FROM Dates
GROUP BY EndDate
答案 1 :(得分:1)
试试这个:
SELECT MIN(iq.StartTime), iq.EndTime
FROM
(
SELECT e1.EventTime AS StartTime, MIN(e2.EventTime) AS EndTime
FROM EventTable e1
LEFT JOIN EventTable e2 ON e2.BooleanField = 0 AND e2.EventTime > e1.EventTime
WHERE e1.BooleanField = 1
GROUP BY e1.EventTime
) iq
GROUP BY iq.EndTime
这将确保您获得每个EndTime的最大间隔。我很确定由于需要两个GROUP BY子句而无法将其简化为单个SELECT查询 - 即使考虑其他示例(通过使用两个不同的聚合函数使用隐式分组,因此等效于此例子)。
答案 2 :(得分:0)
怎么样?
Select s.EventTime StartTime,
e.EventTime EndTime
From EventTable s
Left Join EventTable e
On s.BooleanFiels = 1
And e.BooleanField = 0
And e.EventTime =
(Select Min(EventTime)
From EventTable
Where e.BooleanField = 0
And EventTime > s.EventTime)
Order By s.EventTime