简体   繁体   中英

How to find the difference between two values in same column different rows in mysql

I need to create a query to define changes in price for different version. For example this is the table:

id | price | date| version 
1  | 10    |2020-06-01| 1
1  | 15    |2020-06-12| 2
2  | 4     |2020-06-03| 1
2  | 5     |2020-06-04| 2
2  | 5.5   |2020-06-10| 3

I started to create one query like this:

select t1.price - t2.price from product_price_version t1, product_price_version t2 
where t1.version = t2.version - 1

I need to have as results:

id | price | date| version | difference 
1  | 10    |2020-06-01| 1  | 0
1  | 16    |2020-06-12| 2  | 6
2  | 4     |2020-06-03| 1  | 0
2  | 5     |2020-06-04| 2  | 1
2  | 5.5   |2020-06-10| 3  | 1.5

in the end to add a filter and to show values where difference is greater than 5

You can use lag() :

select
    t.*,
    price - lag(price, 1, price) over(partition by id order by version) diff
from mytable t

In earlier versions, you can self-join or use a correlated subquery:

select
    t.*,
    t.price - coalesce(t1.price, t.price) diff
from mytable t
left join mytable t1 on t1.id = t.id and t1.version = t.version - 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