COUNT and GROUP BY in two columns

Asked

Viewed 2,068 times

4

Personal I am facing a doubt with a particular query, I have searched everywhere on the subject but without success. If there’s any other way to do what I’m trying, I’d appreciate the information

So I’ll illustrate the scenario.

VOUCHER TABLE

inserir a descrição da imagem aqui

In this table I am assigning a serial_lot since the vouchers will be generated in large quantities, each voucher has a Total Time_total.

inserir a descrição da imagem aqui

I managed to create a query where returns me all serial_batch that were created in the last 2 hours and the times that this batch repeats.

SELECT serial_lote, Count(*) FROM vouchers
where (data_criacao BETWEEN DATE_SUB(NOW(), INTERVAL 2 hour) AND NOW())  GROUP BY serial_lote
HAVING Count(*) > 1 
order by serial_lote DESC

ME RETORNA ESSAS INFORMAÇÕES

I need you to return not only the serial lot and the amount of times this batch repeats, but also the total Time_total of each batch. (Lots can only be created with the same Total Time)

Preciso que fique assim

  • http://forum.wmonline.com.br/topic/176750-somar-horas-de-campo-typo-time-no-mysql/ should help you

  • I must have confused you, I don’t want to add the total time.. I wonder what is the time of each Lot.

1 answer

7


The function SUM() does not work with type data Time. That’s why you have to use the functions TIME_TO_SEC and SEC_TO_TIME to convert time to a number of seconds and vice versa.

SELECT serial_lote, Count(*), SEC_TO_TIME( SUM( TIME_TO_SEC( `tempo_total` ) ) ) AS tempoTotal
FROM vouchers
WHERE (data_criacao BETWEEN DATE_SUB(NOW(), INTERVAL 2 hour) AND NOW())  GROUP BY serial_lote
HAVING Count(*) > 1 
ORDER BY serial_lote DESC

EDIT: If you don’t want to add the total time, just add the total time in the SELECT and in the GROUP BY

SELECT serial_lote, tempo_total, Count(*)
FROM vouchers
WHERE(data_criacao BETWEEN DATE_SUB(NOW(), INTERVAL 2 hour) AND NOW())  
GROUP BY serial_lote, tempo_total
HAVING Count(*) > 1 
ORDER BY serial_lote DESC
  • I must have expressed myself wrong, because the goal is to bring only the time of the lot since I can only create a lot with the same time_total. I don’t want to add up, I just want to know that lot 1 is at 3:00 and lot 2 is at 1:00:00

  • @Michelteixeira edited my answer. I hope I understood well

  • 1

    wow! thanks @Estevaoluis is exactly what I need, now I learned.. the issue of select, sorry now I saw that it was a silly thing. Thanks for the help.

Browser other questions tagged

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