Difference of hours query sql server

Asked

Viewed 464 times

2

I have the following data:

2016-10-13 09:04:00.000  1
2016-10-13 20:33:00.000  4
2016-10-14 09:10:00.000  1
2016-10-14 21:04:00.000  4
2016-10-17 09:04:00.000  1
2016-10-17 19:50:00.000  4

How to know the difference between hours between 4 and 1, example:

2016-10-13 09:04:00.000  1
2016-10-13 20:33:00.000  4

My expected result would be around 14 hours, according to example:

20:33
21:33
22:33
23:33
00:33
01:33
02:33
03:33
04:33
05:33
06:33
07:33
08:33
09:04

Namely the numero 4 é o final and the numero 1 é o inicio,need to know the diferença entre final e o inicio.

2 answers

4


Use the DATEDIFF

SELECT DATEDIFF ( HOUR , '2016-10-13 09:04:00.000' , '2016-10-13 20:33:00.000' ) Diferenca

1

I tried to post in SQL Fiddle more ta giving error,follows my solution:

TABLE EXAMPLE:

create table #dados (
    cpf int,
    data datetime ,
    tipo int
)

INSERT EXAMPLE:

insert into #dados (cpf, data, tipo) values
(11111111111, '2016-10-13 09:04:00.000',  1),
(11111111111, '2016-10-13 20:33:00.000',  4),
(33333333333, '2016-10-14 09:10:00.000',  1),
(33333333333, '2016-10-14 21:04:00.000',  4),
(55555555555, '2016-10-17 09:04:00.000',  1),
(55555555555, '2016-10-17 19:50:00.000',  4)

I USED THE NUMBER SO I COULD GROUP:

Agrupei por cpf, pegando a menor data e comparando com a maior data

        select cpf, datediff(hh, min(data), max(data)) as horas
            from #dados
            group by cpf 

Acknowledgments: @Thiago Henrique and Leonardo Caetano

Browser other questions tagged

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