Difference between hours without taking into account the date

Asked

Viewed 920 times

0

Good night,

I have the following code:

WITH
CONSULTA AS (
 SELECT 
    V.CHAPA,
    V.DATA,
    MAX(V.BATIDA) AS MAXBATIDA,
    MIN(V.BATIDA) AS MINBATIDA
      FROM
            ARELBATIDATRANSITOVIEW  AS V                            
        WHERE
          V.CODCOLIGADA = 1
           AND  BATIDA IS NOT NULL 
           AND  YEAR ( V.DATA ) = 2016 
             GROUP BY V.CHAPA,
                       V.DATA
),
CONSULTASEQ AS (
SELECT *, SEQ= ROW_NUMBER() OVERPARTITION BY CHAPA ORDER BY DATA)
  FROM CONSULTA
)
SELECT 
        C1.CHAPA,  
        C1.MAXBATIDA,
        C2.MINBATIDA, 
        DATEDIFF(HOUR, C1.MAXBATIDA, C2.MINBATIDA) AS HORAS,
        'TESTE DE HORAS' AS DESCRICAO
  FROM CONSULTASEQAS C1
       LEFT JOIN CONSULTASEQ AS C2 ON C1.CHAPA = C2.CHAPA AND C1.SEQ = C2.SEQ -1
             WHERE DATEDIFF(HOUR,  C1.MAXBATIDA, C2.MINBATIDA) < 11 
                         ORDER BY C1.MAXBATIDA ASC

He returns to me:

8636;2016-06-04 22:31:00.000;2016-06-06 12:59:00.000;38;TESTE DE HORAS
9042;2016-06-04 22:31:00.000;2016-06-06 12:28:00.000;38;TESTE DE HORAS
9035;2016-06-04 22:32:00.000;2016-06-06 13:31:00.000;39;TESTE DE HORAS

In the hours field he is calculating the difference between the maximum of one hour with the minimum of another, more precise than in fields like this:

8636;2016-06-04 22:31:00.000;2016-06-06 12:59:00.000;38;TESTE DE HORAS
9042;2016-06-04 22:31:00.000;2016-06-06 12:28:00.000;38;TESTE DE HORAS

I need to return the time difference without considering the date, example:

 DIFF ENTRE 22:31:00  E  12:59:00 SEJA:

22:31
23:31
00:31
01:31
02:31
03:31
04:31
05:31
06:31
07:31
08:31
09:31
10:31
11:31
12:31
12:56

That is, without comparing the dates, this would be possible ?

SQL SERVER 2008

  • Tip: also mark as sql-server

1 answer

2


A very simple way is like this:

select CAST((C1.MAXBATIDA-C2.MINBATIDA) as time(0)) Horas

Take this example:

declare @d1 datetime, @d2 datetime
set @d1='20161024 21:18:41.330'
set @d2='20161024 23:28:41.330'
select CAST((@d2-@d1) as time(0)) Horas

Browser other questions tagged

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