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

163
Visualizações
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 Respostas
Responde à pergunta

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 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