Query with datiff returning 0 in sql server result

Asked

Viewed 79 times

0

I have the following appointment:

SELECT 
DATEDIFF(hh, MIN(BATIDA), MAX(BATIDA))AS HORAS
 FROM   ARELBATIDATRANSITOVIEW
WHERE  CHAPA = 3187 
  AND BATIDA IS NOT NULL 
  AND SEQUENCIALBATIDA IN (2,3) 

  GROUP BY DATA

ORDER BY DATA DESC

Example:

HORAS
2
2
2
1
2
2
2
3

Only that it only returns me the hours,I need the other fields that would be:

SELECT 
DATA,
CHAPA,
CODCOLIGADA,
BATIDA,
STATUS,
NATUREZA,
SEQUENCIALBATIDA,
DATEDIFF(hh, MIN(BATIDA), MAX(BATIDA))AS HORAS
 FROM   ARELBATIDATRANSITOVIEW
WHERE  CHAPA = 3187 
  AND BATIDA IS NOT NULL 
  AND SEQUENCIALBATIDA IN (2,3) 

  GROUP BY DATA,CHAPA,CODCOLIGADA,BATIDA,STATUS,NATUREZA,SEQUENCIALBATIDA

ORDER BY DATA DESC

More when I run this query with all fields the field: DATEDIFF(hh, MIN(BATIDA), MAX(BATIDA))AS HORAS returns with 0 Example:

                                                                   HORAS
2016-10-17 00:00:00.000 123  1  2016-10-17 12:10:00.000 C   1   2   0
2016-10-17 00:00:00.000 123  1  2016-10-17 14:20:00.000 C   0   3   0
2016-10-14 00:00:00.000 123  1  2016-10-14 11:48:00.000 C   1   2   0

What could be ?

What my interest in this field hour,listar resultados > 2

1 answer

1


This must occur because DATEDIFF altarpiece INT, and may be making some rounding.
Try to return in seconds and it will work, see the example:

declare @d1 datetime, @d2 datetime

set @d1='2016-10-19 15:40:52.847'
set @d2='2016-10-19 15:42:52.847'

-- Aqui retorna zero
select DATEDIFF(hh, @d1, @d2) AS HORAS

-- Aqui retorna certo, 2horas
select DATEDIFF(ss, @d1, @d2)/60 AS HORAS

In your code:

DATEDIFF(ss, MIN(BATIDA), MAX(BATIDA))/60 AS HORAS
  • I got it and it worked, Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.