0
Hello.
I am doing a SELECT to return the last 06 months, showing the count of records (in the example: sales), grouping by year-month.
My query currently looks like this:
**Schema (MySQL v5.7)**
CREATE TABLE vendas (
id INT NOT NULL,
data_venda DATE NOT NULL,
PRIMARY KEY (id),
UNIQUE (id)
);
INSERT INTO vendas
(id, data_venda)
VALUES
(1, '2020-10-01'),
(2, '2020-10-01'),
(3, '2020-12-01'),
(4, '2020-12-01'),
(5, '2020-12-01'),
(6, '2020-12-01'),
(7, '2021-02-01'),
(8, '2021-02-01'),
(9, '2021-02-01'),
(10, '2021-02-01'),
(11, '2021-02-01'),
(12, '2021-03-01'),
(13, '2021-03-01'),
(14, '2021-03-01'),
(15, '2021-03-01'),
(16, '2021-04-01');
Query #1
SELECT
DATE_FORMAT(data_venda, "%Y-%m") AS ano_mes,
COUNT(id)
FROM
vendas
WHERE
/* Utilize o NOW para mudar automaticamente,
* deixei fixo 2021-04-30 para o exemplo
* ainda funcionar no futuro.
*/
/* data_venda >= DATE_SUB(NOW(), INTERVAL 6 MONTH) */
data_venda >= DATE_SUB('2020-04-30', INTERVAL 6 MONTH)
GROUP BY
DATE_FORMAT(data_venda, "%Y-%m");
anomes | COUNT(id) |
---|---|
2020-12 | 4 |
2021-02 | 5 |
2021-03 | 4 |
2021-04 | 1 |
Note that, to be the last 06 months, should return also the month 2020-11 and 2021-01, showing as 0 (zero). Thus:
anomes | COUNT(id) |
---|---|
2020-11 | 0 |
2020-12 | 4 |
2021-01 | 0 |
2021-02 | 5 |
2021-03 | 4 |
2021-04 | 1 |
I have already thought of doing the treatment after the query, directly in the system programming (create a function to correct the return of SELECT, direct in PHP, for example). But it seems to be more readable and simple if the consultation is already complete (with zero months).
I believe that the correction goes through some SUBSELECT that builds the last 06 months and then combines with my current SELECT (example above), but I’m not able to do it. I saw some questions here, but I couldn’t apply the answer either. Some talked about creating a trial or adjusting the month within a fixed year, but note that in this case there are two years involved.
Thank you to anyone who can assist.
This answers your question? Return results for all months of the interval
– Sorack
Thanks, Sorack. But I still have the problem of the year changing, right? Try applying with the creation of the 12-month list created in the given answer, but the query does not know which year the created month belongs to. Maybe the output is to create a base table of dates (leave it there in my database), with all possible months and years (until a very long date in the future), and filter from it. But I would like the support of those who have more knowledge, whether this is a good option or would be an easy/gambiarra exit.
– Jean Barbosa
Which version of Mysql you are using?
– Sorack
v5.7, same as in the example in the question.
– Jean Barbosa