Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

184
Vistas
Select row where column is different from previous row

I am trying to write a query to track the changes of a boolean column in a table. The table looks like this

ClientHistory
-------------------------------------------------------------
| id | client_id | client_name | is_active    |   Timestamp |
-------------------------------------------------------------
| 1 |    1       |Example Client|    True     |   06/15/2020|
-------------------------------------------------------------
| 2 |    1       |Client Change |     True    |   06/16/2020|
-------------------------------------------------------------
| 3 |    1       |Client Change |   False     |  06/17/2020 |

So what i would want is row 3 where the is_active changed to false. Then after that i would want the next row where it changed to true again.

This is what i tried:

        SELECT a.*
        FROM client_history AS a
        WHERE a.is_active <>
            ( SELECT b.is_active
                FROM client_history AS b
                WHERE a.client_id = b.client_id
                AND a.timestamp > b.timestamp
                ORDER BY b.timestamp DESC
                LIMIT 1
            ) 

So the subquery is trying to get the previous row of the same client_id by getting the most recent timestamp before it . Then in query check if is_active does not equal the is_active from the previous row. But this is not working as planned. I expect as I trigger acttive/inactive it should be alternating in this query but it is not. Anybody got any tips?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Use window functions!

select ch.*
from (select ch.*,
             lag(is_active) over (partition by client_id order by timestamp) as prev_is_active
      from client_history ch
     ) ch
where is_active <> prev_is_active;
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda