简体   繁体   中英

SQL - Get previous item and difference between dates

I have the following table:

| account_id | movie_title | stream_date |
| ---------- | ----------- | ----------- |
| abc123     | Movie_1     | 2021-11-01  |
| abc123     | Movie_2     | 2021-11-20  |
| abc123     | Movie_3     | 2021-11-12  |

I need to build a query that gets as result:

| account_id | movie_title | days_past   |
| ---------- | ----------- | ----------- |
| abc123     | Movie_2     | 8           |

Being some fixed parameters:

De difference is always between stream_date of Movie_3 and the previous record for the same ID.

You can use LAG() . For example:

select
  account_id,
  movie_title,
  datediff(lag(stream_date) 
      over(partition by account_id order by stream_date),
    stream_date
  ) as days_past
from t
where movie_title = 'Movie_3'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM