Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining two datetime fields into two separate columns in T-SQL

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!

like image 370
EskoM Avatar asked Aug 18 '26 04:08

EskoM


1 Answers

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
like image 117
Adriaan Stander Avatar answered Aug 21 '26 02:08

Adriaan Stander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!