【问题标题】:How to find the difference between two values in same column different rows in mysql如何在mysql中查找同一列不同行中的两个值之间的差异
【发布时间】:2020-10-14 14:31:16
【问题描述】:

我需要创建一个查询来定义不同版本的价格变化。 例如这是表格:

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

我开始像这样创建一个查询:

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

我需要有结果:

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

最后添加一个过滤器并显示差异大于 5 的值

【问题讨论】:

  • 可以使用 lag() 函数

标签: mysql sql select window-functions


【解决方案1】:

你可以使用lag():

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

在早期版本中,您可以自联接或使用相关子查询:

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

【讨论】:

  • mysql 错误:您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以了解在 '(partition by id order by version) diff 附近使用的正确语法
  • @Botalbania:您的 MySQL 版本不支持窗口函数。您可以改用第二个查询。
  • 它适用于第二个,我如何添加条件,其中 t.price - coalesce(t1.price, t.price) >100 和最后一个版本的产品,你能帮我吗?
  • @Botalbania:只需添加一个where 子句:where t.price - coalesce(t1.price, t.price) > 5
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多