简体   繁体   中英

How do I select row with the most recent reduction in a column value from same columns value in previous row?

I have a set of inventory data where the amount increases at a given rate. For example, the inventory increases by ten units every day. However, from time to time there will be an inventory reduction that could be any amount. I need a query that can find me the most recent inventory reduction and return to me the sum of that deduction.

My table holds date and amount for numerous item id's. In theory what I am trying to do is select all amounts and dates for a given item ID, and then find the difference between the most recent reduction between two days inventory. Due to the fact that multiple items are tracked, there is no guarantee that the id column will be consecutive for a set of items.

Researching to find a solution to this has been completely overwhelming. It seems like window functions might be a good route to try, but I have never used them and don't even really have a concept of where to start.

While I could easily return the amounts and do the calculation in PHP, I feel the right thing to do here is harness SQL but my experience with more complex queries is limited.

ID | ItemID | Date       | Amount 
1      2      2019-05-05   25
7      2      2019-05-06   26
34     2      2019-05-07   14
35     2      2019-05-08   15
67     2      2019-05-09   16
89     2      2019-05-10   5
105    2      2019-05-11   6

Given the data above, it would be nice to see a result like:

item id | date       | reduction
2         2019-05-10   11

This is because the most recent inventory reduction is between id 67 and 89 and the amount of the reduction is 11 on May 10th 2019.

In MySQL 8+, you can use lag() :

select t.*, (prev_amount - amount) as reduction
from (select t.*,
             lag(amount) over (partition by itemid order by date) as prev_amount
      from t
     ) t
where prev_amount > amount
order by date desc
limit 1;

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