I have a table like this -
row_no | Movie. | movie_start_time | movie_end_time |
---|---|---|---|
1 | A | 2021-02-01 01:00:00 | 2021-02-01 02:00:00 |
2 | B | 2021-02-01 01:00:00 | 2021-02-01 02:00:00 |
3 | A | 2021-02-01 01:30:00 | 2021-02-01 02:30:00 |
4 | A | 2021-02-01 01:30:00 | 2021-02-01 02:30:00 |
5 | A | 2021-02-01 02:15:00 | 2021-02-01 03:15:00 |
6 | B | 2021-02-01 02:15:00 | 2021-02-01 03:15:00 |
7 | A | 2021-02-01 04:15:00 | 2021-02-01 05:15:00 |
I want to add one additional column to the table which has difference between previous play time and current play time for the same movie. I also have a condition that previous play time and current play time shouldn't be overlapping. So in above scenario, results should look like below:
row_no | Movie. | movie_start_time | movie_end_time. | last_play |
---|---|---|---|---|
1 | A | 2021-02-01 01:00:00 | 2021-02-01 02:00:00 | - |
2 | B | 2021-02-01 01:00:00 | 2021-02-01 02:00:00 | - |
3 | A | 2021-02-01 01:30:00 | 2021-02-01 02:30:00 | - |
4 | A | 2021-02-01 01:30:00 | 2021-02-01 02:30:00 | - |
5 | A | 2021-02-01 02:15:00 | 2021-02-01 03:15:00 | 15 minutes |
6 | B | 2021-02-01 02:15:00 | 2021-02-01 03:15:00 | 15 minutes |
7 | A | 2021-02-01 04:15:00 | 2021-02-01 05:15:00 | 60 minutes |
I tried writing below query for getting the previous movie_end_time so that I can calculate the difference later :
select movie, movie_start_time, movie_end_time, lag(movie_end_time) over (partition by movie order by movie_start_time) prev_end_time from table where prev_end_time <= movie_start_time
But this doesn't work since we can't add where clause with window functions. Is there any other way to solve this problem ?