Let's say I have two entities: Event and Activity
An Event is something that happens at (seemingly) random times, like Sunrise, Sunset, Storm, Fog, etc.
I have a table for this:
create table Event (
eventKey int,
eventDesc varchar(100),
started datetime
)
EventKey | EventDesc | Started
1 "Sunset" 2009-07-03 6:51pm
2 "Sunrise" 2009-07-04 5:33am
3 "Fog" 2009-07-04 5:52pm
4 "Sunset" 2009-07-04 6:49pm
5 "Full Moon" 2009-07-04 10:12pm
6 "Sunrise" 2009-07-05 5:34am
Then I have a table of activities that people participated in, and which events they relate to (i.e. an action could be long-running and cross multiple events: "Camp-out over the weekend"):
create table EventTask (
activityKey int,
activityDesc varchar(100),
startEventKey int,
endEventKey int
)
ActivityKey | ActivityDesc | StartEventKey | EndEventKey
123 "Camp-out" 1 5
234 "Drive home" 6 6
I want to output a timeline of actions that are marked by the events that happened:
ActivityKey | ActivityDesc | EventKey | EventDesc
123 "Camp-out" 1 "Sunset"
123 "Camp-out" 2 "Sunrise"
123 "Camp-out" 3 "Fog"
123 "Camp-out" 4 "Sunset"
123 "Camp-out" 5 "Full Moon"
234 "Drive Home" 6 "Sunrise"
Is it possible to write a query that will do this in linear time, similar to this question? Please also recommend indexes or any other optimizations you can think of. The current solution is written in C#, but I would love a fast SQL solution.
What is the optimal query to do this?