Skip to content
Advertisement

SQL query to find the concurrent sessions based on start and end time

Below is a sample dataset showing TV sessions of each TV set of each household. Household “111” switch on their TV “1” at 500 and switch it off at 570. However, this has been captured in the data as 2 separate rows. You will have to write a query to convert this into a single row. Similar modification needs to be made to all other subsequent occurrences. Please note that a single valid TV session can be split into more than 2 rows as well (As shown by rows 5-8).

Input : Table [session]

Expected Output :-

I tried to find the lead time and find the difference and calculate the difference between that and the End time and thought I could group by but then that logic wont work since we dont just want the start and end time but even the gaps in the sessions. I’m stuck with the logic. Could someone tell how to proceed further ?

Advertisement

Answer

Here is a way to get this done

In the data block i create groups which is defined as any record whose previous end_time doenst match with my start_time and assign a group_number to it if its different, else i keep it same.

After that in the main block i group by this group_number, along with the household_id,tv_set_id to get the results.

db fiddle link https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=ba5ade186ebc3cf693c505d863691670

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement