Reputation: 109
I am working with the Sakila video rental database that comes preloaded with MySQL.
I am trying to find the average number of days each video sits on the shelf before it is rented again.
In the rentals
table you have the rental_id
for each rental transaction, the inventory_id
corresponding to the item that was rented, as well as the rental_date
and return_date
.
For each rental transaction I would like to look at the rental_date
and find the difference from the return_date
of the previous occurrence of the same inventory_id
.
I know LAG()
and LEAD()
might be useful here, but I have no idea how to make it only consider other rows with the same inventory_id
.
Sample data:
rental_id inventory_id rental_date return_date
-------------------------------------------------------
1 115 01-01-2005 01-05-2005
2 209 01-01-2005 01-04-2005
3 115 01-06-2005 01-10-2005
4 209 01-09-2005 01-14-2005
5 209 01-15-2005 01-20-2005
6 115 01-16-2005 01-20-2005
Desired output:
rental_id inventory_id rental_date return_date days_on_shelf
------------------------------------------------------------------------
1 115 01-01-2005 01-05-2005 NULL
2 209 01-01-2005 01-04-2005 NULL
3 115 01-06-2005 01-10-2005 1
4 209 01-09-2005 01-14-2005 5
5 209 01-15-2005 01-20-2005 1
6 115 01-16-2005 01-20-2005 6
Thank you to June7. The correct code should look like this:
SELECT
rental.rental_id,
rental.inventory_id,
inventory.film_id,
rental.rental_date,
rental.return_date,
IF(@lastid = rental.inventory_id,
DATEDIFF(rental.rental_date, @lastreturn),
NULL) AS days_on_shelf,
@lastid:=rental.inventory_id,
@lastreturn:=rental.return_date
FROM
rental
JOIN
inventory ON rental.inventory_id = inventory.inventory_id
ORDER BY rental.inventory_id , rental.rental_date
Upvotes: 0
Views: 97
Reputation: 1270463
You seem to just want lag()
:
select t.*,
datediff(rental_date,
lag(return_date) over (partition by inventory_id order by rental_date)
) as days_on_shelf
from t
Upvotes: 2