I have a table with the two Start and End fields of Tipo de dados Time
.
Example of records I have in the table:
- 09:30:00 10:00:00
- 10:00:00 11:00:00
- 11:00:00 12:00:00
As I show, I have full hours and half hours, as you can only have 20 minutes or 45 minutes for example.
Now I want to make the time difference and then add up the total hours per customer.
The problem is that when I do not have whole hours, for example I have 5 records of the same client of 30 minutes, so it's 2:30 minutes, the query shows the result as 1:50 because it is adding 30 five times.
Query:
SELECT C.codigoutente,
C.nome AS Utente,
C.descricaovalencia AS Valência,
REPLACE(CAST(SUM(SEC_TO_TIME(C.Minutos))/100 AS DECIMAL (15,2)), '.', ':') AS 'Horas Consumidas',
CONVERT(CONCAT(CAST(SUM(C.Valor) AS DECIMAL (15,2)), '€'), char(8)) AS 'Valor Total'
FROM
(SELECT B.codigoutente,
B.nome,
B.descricaovalencia,
B.'Data',
B.Minutos,
IF(B.nome = 'CLASSE', (B.Minutos*10)/60, (B.Minutos*12)/60) AS Valor
FROM
(SELECT A.codigoutente,
A.nome,
A.descricaovalencia,
A.'Data',
A.'Horas Consumidas',
CAST(TIME_TO_SEC(A.'Horas Consumidas')/60 AS DECIMAL(15,0)) AS Minutos
FROM
(SELECT centrodb.registoFisioterapia.id,
centrodb.utentes.codigoutente,
centrodb.utentes.nome,
centrodb.utentes.descricaovalencia,
centrodb.registoFisioterapia.'Data',
Inicio,
Fim,
centrodb.colaboradores.Nome AS Colaborador,
TimeDiff(TIME_FORMAT(Fim,'%H:%i'), TIME_FORMAT(Inicio,'%H:%i')) AS 'Horas Consumidas'
FROM centrodb.registoFisioterapia LEFT OUTER JOIN centrodb.utentes
ON centrodb.utentes.Id = centrodb.registoFisioterapia.utente
LEFT OUTER JOIN colaboradores
ON centrodb.colaboradores.codigo = centrodb.registoFisioterapia.Nome) AS A) AS B
) AS C
GROUP BY C.codigoutente, C.nome, C.descricaovalencia
The correct result should then be 2:30 minutes and not 1:50 minutes. Can anyone help?
Change:
SELECT B.codigoutente,
B.nome,
B.descricaovalencia AS Valência,
SUM(B.Minutos) AS 'Horas Consumidas',
CONVERT(CONCAT(CAST(SUM(B.Valor) AS DECIMAL (15,2)), '€'), char(8)) AS 'Valor Total'
FROM
(SELECT A.codigoutente,
A.nome,
A.descricaovalencia,
A.'Data',
A.'Minutos',
IF(A.nome = 'CLASSE', (A.'Minutos'*10), (A.'Minutos'*12)) AS Valor
FROM
(SELECT centrodb.registoFisioterapia.id,
centrodb.utentes.codigoutente,
centrodb.utentes.nome,
centrodb.utentes.descricaovalencia,
centrodb.registoFisioterapia.'Data',
Inicio,
Fim,
centrodb.colaboradores.Nome AS Colaborador,
CAST(TIME_TO_SEC(TiMEDiff(TIME_FORMAT(Fim,'%H:%i'), TIME_FORMAT(Inicio,'%H:%i')))/60/60 AS DECIMAL(15,2)) AS 'Minutos'
FROM centrodb.registoFisioterapia LEFT OUTER JOIN centrodb.utentes
ON centrodb.utentes.Id = centrodb.registoFisioterapia.utente
LEFT OUTER JOIN colaboradores
ON centrodb.colaboradores.codigo = centrodb.registoFisioterapia.Nome) AS A) AS B
GROUP BY B.codigoutente, B.nome, B.descricaovalencia