简体   繁体   English

如何找到 mysql 中同一列不同行中的两个值之间的差异

[英]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.

相关问题 在MySQL中查找同一列的两个连续行之间的差异 - Find difference between two consecutive rows of same column in mysql 如何在mysql中找到两行之间的区别 - how to find the difference between two rows in mysql 在同一列中的两行中两次之间的差异 - MySql - Difference in seconds between two times in two rows in the same column - MySql 如何在MySQL的同一张表上的两个不同输入值之间的两个不同列之间选择行 - How to select rows between two different columns with two different input values on same table on mysql 在MySQL的同一列中查找两个值之间的差异 - Finding the difference between two values in the same column in MySQL SQL-如何查找包含时间戳的同一列的两行之间的差异 - SQL - How to find difference between two rows of same column containing timestamps 如何找到同一表中两行之间的差异并列出不匹配的记录? mysql在表中查找不匹配的行 - mysql How to Find Difference between two rows in same table and list the Unmatched Records? mysql finding unmatched rows in a table 从数据库(MySQL)获取同一列的两行不同值的行 - Fetch two rows of different values of the same column from database (MySQL) MySQL - 找到同一个表的行之间的差异 - MySQL - find difference between rows of the same table 如何通过 ids 查找 Mysql(版本 5.6)中两行之间的差异 - How to find the difference between two rows in Mysql (version 5.6) by ids
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM