Necesito crear una consulta para definir cambios en el precio de una versión diferente. Por ejemplo esta es la tabla:
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| 3Empecé a crear una consulta como esta:
select t1.price - t2.price from product_price_version t1, product_price_version t2 where t1.version = t2.version - 1Necesito tener como resultados:
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.5al final para agregar un filtro y mostrar valores donde la diferencia es mayor a 5
Puedes usar lag() :
select t.*, price - lag(price, 1, price) over(partition by id order by version) diff from mytable tEn versiones anteriores, puede unirse a sí mismo o usar una subconsulta correlacionada:
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