[英]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最后添加一个过滤器并显示差异大于 5 的值
You can use lag()
:您可以使用
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.