Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

426
Visualizações
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

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use 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
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda