我需要创建一个查询来定义不同版本的价格变化。 例如,以下是表:
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()
:
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