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

159
Vistas
MYSQL difference between two datetime

I have the following table.

table1:

id_user | action |  time 
--------+--------+----------------------
1       | 2      | '2009-05-18 11:45:42'
1       | 2      | '2009-05-18 11:45:45'
1       | 3      | '2009-05-18 11:45:50'
1       | 2      | '2009-05-18 11:46:50'

And I want to achieve result where the column timediff contains timediff with the previous row in seconds.

table2

id_user | action | timediff
--------+--------+----------
1       | 2      | 3
1       | 2      | 5
1       | 3      | 60

I tried this query, but It did not work:

SELECT
    id_user,action, 
    TIMESTAMPDIFF(SECOND,LEAD(time),time) OVER (PARTITION BY id_user, ORDER BY time) AS timediff
FROM table1

... but it throws an error. :/

I read other answers, but I didn't see one that use LEAD or LAG with TIMESTAMPDIFF simultaneously.

Thanks in advance.

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

0

Your syntax is wrong, you must use this:

SELECT id_user,
       action, 
       TIMESTAMPDIFF(
         SECOND, 
         time, 
         LEAD(time) OVER (PARTITION BY id_user ORDER BY time)
       )  AS timediff 
FROM table1

The TIMESTAMPDIFF() function's 2nd and 3d arguments are datetime expressions and the 2nd is subtracted from the 3d.

See the demo.
Results:

| id_user | action | timediff |
| ------- | ------ | -------- |
| 1       | 2      | 3        |
| 1       | 2      | 5        |
| 1       | 3      | 60       |
| 1       | 2      |          |
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