Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically un-flatten table using SQL

My subject line is probably not the best, but here's what I'm trying to do:

I have a table with start and end times:

Event   Start     End
-------------------------    
event1  2:30 PM   3:00 PM
event2  3:05 PM   3:30 PM
event3  2:45 PM   3:10 PM

I want to write a SQL command (in Oracle) which will result in:

Event   Type    Time
-------------------------    
event1  START   2:30 PM
event3  START   2:45 PM
event1  END     3:00 PM
event2  START   3:05 PM
event3  END     3:10 PM
event2  END     3:30 PM

Basically, I need to order the times and know the event it's for and whether it's the start or end time. I have a feeling this can be accomplished with some fancy SQL, but I'm having trouble thinking of how to do it.

Thanks!

like image 562
Paul Avatar asked Sep 22 '26 12:09

Paul


1 Answers

Nothing fancy but a simple UNION would suffice

SELECT Event, 'START', Start AS Time
FROM   ATable
UNION ALL
SELECT Event, 'END', End AS Time
FROM   ATable
ORDER BY
       Time

If you like to get a bit more fancy, UNPIVOT is another option

SELECT  Event, Type, Time
FROM    ATable
UNPIVOT (Time FOR Type IN (Start, [End])) AS unpvt
ORDER BY  
        Time
like image 93
Lieven Keersmaekers Avatar answered Sep 24 '26 05:09

Lieven Keersmaekers



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!