I would like to know how I can query the MySql database and group the records by year and month.
At the moment I first make a query to get the year records, then for each year I use a for () to filter the results per month within that year. For example:
$ano = sql("SELECT DISTINCT YEAR(dataCadastro) as 'ano' FROM tabela");
foreach ($ano as &$row) {
$ano = $row['ano'];
for ($i=1; $i<=12; $i++) {
$item = sql("SELECT id, ... FROM tabela WHERE YEAR(dataCadastro) = '$ano' AND MONTH(dataCadastro) = '$i'");
$row[$i] = $item;
}
}
Searching on the subject I saw that I could use GROUP BY
, but when I try to use it, the query returns empty even though I'm sure it would have results. For example:
$grupo = sql("SELECT id, ... FROM tabela"); //Retorna os dados corretamente
$grupo = sql("SELECT id, ... FROM tabela GROUP BY YEAR(dataCadastro)"); //Retorna vazio
The date in the database is as datetime
, eg 2016-11-09 17:30:00
Is there any way to get this result using GROUP BY
? Because of the searches I've done, I've noticed that, but when I try to run, I can not get the results.
Remembering that the first mode I showed (with the use of foreach
) I can get the results as I wish, but I would like to simplify the process.