For the question, Let’s say I have a table that holds the following data :
1) Name
2) Mood
3) DateTime
I could insert records like :
Andy Happy '11.06.2012 - 14.06.07' -- Inserted on 11.06.2012 @ 19:12.32
Arthur Angry '11.06.2012 - 15.06.57' -- Inserted on 11.06.2012 @ 17:12.32
Andy Sad '11.06.2012 - 14.34.05' -- Inserted on 11.06.2012 @ 17:12.32
Arthur Happy '11.06.2012 - 13.34.05' -- Inserted on 11.06.2012 @ 14:12.32
I would like to get the “duration” information related to these moods changes !
My table holds thousands of hundred or records and I cannot afford having a process that takes too much time. What would be the best way of calculating this ?
- Trigger “After insert”, filling a “Duration” column ?
- Stored procedure that fill a previously created “Duration” column ?
- Calculated column ?
- A view (I already tried that and it takes more than 2 seconds to display, which is totally unacceptable)
- Another idea ?
Thanks for your help !
Important edit :
The mood records arrive grouped into packet and we cannot be sure that already inserted records have smaller dates! (see the above comments next to my records)
A possible SQL version:
Result:
Your test data:
Edit Self-Joining a
CTEseems to be a very bad idea (“If you self join the CTE it will kill you“). I’ve tested my query with 500000 records in a temporary table and cancelled the query after 30 minutes.Here’s a much faster approach(4 seconds for all) using a sub-query (with your commented schema):