Mysql group by month and year between dates

Asked

Viewed 119 times

1

I have a table called agenda in Mysql like this (the date is in the database in date format, I put in Portuguese format just to make it easier the example):

inserir a descrição da imagem aqui

I need a query that lists the months and years that have registered dates between the day and the day ending, in the example of the table above what would be listed:

01/2020
02/2020
03/2020
04/2020
05/2020
07/2020

Note that the month 06 of 2020 does not appear, because there are no registered days in this month.

I tried something like this:

SELECT * FROM agenda GROUP BY (BETWEEN agenda.dia_inicio AND agenda.dia_termino)

I know there is the function between, but this is not how it is used. How to do?

  • 1

    Use a GROUP BY YEAR(agenda.dia_inicio), MONTH(agenda.dia_inicio).

2 answers

2


Try it this way.

SELECT * FROM agenda where (BETWEEN agenda.dia_inicio AND agenda.dia_termino) GROUP BY MONTH(dia_termino), DAY(dia_termino)

0

The way you are doing it is not correct, first the date format should be "2020-03-03" (YEAR-MONTH-DAY) for either operations with date work. Then you should choose a column to group, up to where I if it is not possible to group by date range, you should do something like:

SELECT * FROM agenda where (BETWEEN agenda.dia_inicio AND agenda.dia_termino) GROUP BY genda.dia_inicio

or

SELECT * FROM agenda where (BETWEEN agenda.dia_inicio AND agenda.dia_termino) GROUP BY genda.dia_termino
  • The date is in the right format, I put it in Portuguese format only to explain. But in your example gave error, the same as mine: Fatal error: Uncaught Exception 'Pdoexception' with message 'SQLSTATE[42000]: Syntax error or access Violation: 1064 You have an error in your SQL syntax; check the manual that Corresponds to your Mysql server version for the right syntax to use near 'BETWEEN agenda.dia_home AND agenda.dia_termino) GROUP BY agenda.dia_home'

Browser other questions tagged

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