How to group by day of the month in Mysql

Asked

Viewed 659 times

3

I would like to know how to do a select where I can display in columns the employee input and output records in the lobby.
The table looks like this:

╔════╦══════╦═════════════════════╦═════════════════════╗
║ ID ║ Nome ║ DHEntrada           ║ DHSaída             ║
╠════╬══════╬═════════════════════╬═════════════════════╣
║ 1  ║ João ║ 2017-02-06 11:05:22 ║ 2017-02-06 14:05:22 ║
║ 2  ║ José ║ 2017-02-06 08:05:22 ║ 2017-02-06 10:05:22 ║
║ 3  ║ João ║ 2017-02-06 08:05:22 ║ 2017-02-06 09:05:22 ║
║ 2  ║ José ║ 2017-02-05 12:05:22 ║ 2017-02-05 18:05:22 ║
║ 2  ║ José ║ 2017-02-05 08:44:22 ║ 2017-02-05 10:01:22 ║
╚════╩══════╩═════════════════════╩═════════════════════╝

The consultation would be:

╔═════╦════════════╦═══════════╦════════════╦═══════════╗
║Nome ║ Entr 05/02 ║ Saí 05/02 ║ Entr 06/02 ║ Saí 06/02 ║
╠═════╬════════════╬═══════════╬════════════╬═══════════╣
║João ║     0      ║     0     ║     2      ║   2       ║
║José ║     2      ║     2     ║     1      ║   1       ║
╚═════╩════════════╩═══════════╩════════════╩═══════════╝
  • 1

    Will you have the dates set or do you want everything to be created dynamically? And what does 0, 1 and 2 mean in the second table?

  • 1

    Wow!!! At the time I did not see these ASCII tables!!!

  • @Sorack The dates are dynamic yes. The numbers 0.1 and 2 are the incidence of input and the outgoing incidences of each element (in the case of "John" and "Joseph") on the specified dates.

1 answer

1


Basically what you need is a table pivot in MYSQL.

Normally this requires some complexity in the query such as knowing all the columns that the query will return. in the link below Voce can know a little more about pivot table in MYSQL

http://www.artfulsoftware.com/infotree/qrytip.php?id=78

Although it is not exactly the pivot because Mysql does not have the function of pivot (unless it is a new feature) then in this case you will have to do various functions of aggregations.

example:

select nome
       ,count(case when day(dataEntrada) = 1 then 1 else 0 end) as [dia 1 do mes]
       ,count(case when day(dataEntrada) = 2 then 1 else 0 end) as [dia 2 do mes]
       ....
       ,count(case when day(dataEntrada) = 31 then 1 else 0 end) as [dia 31 do mes]


from tabelaPonto
where month(dataEntrada) = 1
group by nome;

there are ways to improve this query but I would go that way.

  • Wow!!! Thanks so much! I’ll take the test here. Thank you.

  • arrange! if possible after the test post if the proposed solution has been useful to you

  • It worked really well! Thank you, man! Took me out of a week’s suffocation by cracking my head!

  • @Snowbg Was the answer helpful to you? If so, be sure to mark it so it can be used if someone has a similar question!

  • 1

    @Sorack! Done. Thank you.

Browser other questions tagged

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