G
The thing already begins strange by date and time being in separate columns and being of the type sweep(?)(I suppose so). I grouped as I understood, it was to take the shortest hour of a drive and the largest date of a drive and calculate the amount of time in them. If anything differs from that, please explain better. http://sqlfiddle.com/#!6/1dda8/1 As it is not in the comments, my suggestion:select MATRICULA_COLABORADOR, ACIONAMENTO,
convert(datetime, MIN(DATA_INICIO_HE) + ' ' + MIN(HORA_INICIO_HE), 103) as data_hora_inicio_minimo,
convert(datetime, MAX(DATA_TERMINO_HE) + ' ' + MAX(HORA_TERMINO_HE), 103) as data_hora_termino_maximo,
concat(
format(datediff(
second,
convert(datetime, MIN(DATA_INICIO_HE) + ' ' + MIN(HORA_INICIO_HE), 103),
convert(datetime, MAX(DATA_TERMINO_HE) + ' ' + MAX(HORA_TERMINO_HE), 103)
) / 60 / 60, '00'), ':',
format(datediff(
second,
convert(datetime, MIN(DATA_INICIO_HE) + ' ' + MIN(HORA_INICIO_HE), 103),
convert(datetime, MAX(DATA_TERMINO_HE) + ' ' + MAX(HORA_TERMINO_HE), 103)
) / 60 % 60, '00') , ':',
format(datediff(
second,
convert(datetime, MIN(DATA_INICIO_HE) + ' ' + MIN(HORA_INICIO_HE), 103),
convert(datetime, MAX(DATA_TERMINO_HE) + ' ' + MAX(HORA_TERMINO_HE), 103)
) % 60, '00')
) as tempo
from tabela
group by MATRICULA_COLABORADOR, ACIONAMENTO;
edit (li in the comments you wanted to summarize by license plate), still using the above sql:select MATRICULA_COLABORADOR, SUM(segundos) as total_segundos,
concat(
format(SUM(segundos) / 60 / 60, '00'), ':',
format(SUM(segundos) / 60 % 60, '00') , ':',
format(SUM(segundos) % 60, '00')
) as total_tempo
from (select MATRICULA_COLABORADOR, ACIONAMENTO,
convert(datetime, MIN(DATA_INICIO_HE) + ' ' + MIN(HORA_INICIO_HE), 103) as data_hora_inicio_minimo,
convert(datetime, MAX(DATA_TERMINO_HE) + ' ' + MAX(HORA_TERMINO_HE), 103) as data_hora_termino_maximo,
concat(
format(datediff(
second,
convert(datetime, MIN(DATA_INICIO_HE) + ' ' + MIN(HORA_INICIO_HE), 103),
convert(datetime, MAX(DATA_TERMINO_HE) + ' ' + MAX(HORA_TERMINO_HE), 103)
) / 60 / 60, '00'), ':',
format(datediff(
second,
convert(datetime, MIN(DATA_INICIO_HE) + ' ' + MIN(HORA_INICIO_HE), 103),
convert(datetime, MAX(DATA_TERMINO_HE) + ' ' + MAX(HORA_TERMINO_HE), 103)
) / 60 % 60, '00') , ':',
format(datediff(
second,
convert(datetime, MIN(DATA_INICIO_HE) + ' ' + MIN(HORA_INICIO_HE), 103),
convert(datetime, MAX(DATA_TERMINO_HE) + ' ' + MAX(HORA_TERMINO_HE), 103)
) % 60, '00')
) as tempo, datediff(
second,
convert(datetime, MIN(DATA_INICIO_HE) + ' ' + MIN(HORA_INICIO_HE), 103),
convert(datetime, MAX(DATA_TERMINO_HE) + ' ' + MAX(HORA_TERMINO_HE), 103)
) segundos
from tabela
group by MATRICULA_COLABORADOR, ACIONAMENTO) as temp group by MATRICULA_COLABORADOR;
If that's it, let me know that I can improve the final sql.