简体   繁体   中英

How to subtract one column from another column finding the previous occurrence of the same id?

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

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

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