I'm trying to create a view that displays events with start and end time. This view should be gathered from an existing table that only has an event time field and event type field.
So the current EventTable looks like this:
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
And the result set should look like this
StartTime | EndTime
-----------------------------
1/1/2010 6:00AM 1/2/2010 6:00AM
1/3/2010 6:00AM 1/5/2010 6:00AM
So the view should display the periods that the boolean field is true.
Is there a simple solution to achieve this in SQL Server 2008?
Thank you for help!
you could try something like (full example)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With