SELECT from the last 365 days (12 months) in sql

Asked

Viewed 764 times

3

Good morning! I’m having some difficulty making one SELECT selecting data from the last 365 days (12 months).

What I want you to show is: in the last 12 months you have to show (per month) a number (in this case the sum of id created that same month).

I think the mistake is in this part of the code:

BETWEEN now() AND DATE_ADD(now(), INTERVAL -12 MONTH)

But I’m not sure because Workbench no errors! Just shows nothing!

My code is this::

SELECT COUNT(id) AS id, DATE_FORMAT(create_time, '%m-%Y') AS data_mes
FROM ticket
WHERE ticket_state_id = 2 AND create_time BETWEEN now() AND DATE_ADD(now(), INTERVAL -12 MONTH)
GROUP BY MONTH(create_time);
  • 1

    Do not put resolved in the question title, which is not the way the site works. You indicate if the question has been resolved by accepting an answer by clicking on the green mark next to it

  • 1

    I appreciate the information! Since I am still recent on the site. So I can only accept my own answer in 2 days.

2 answers

4


Thank you very much to all those who are willing to help me, but fortunately I have already solved.

The code to solve is here:

SELECT COUNT(id) AS id, DATE_FORMAT(create_time, '%m-%Y') AS data_mes
FROM ticket
WHERE ticket_state_id = 2 AND create_time BETWEEN DATE_ADD(now(), INTERVAL -12 MONTH) AND now()
GROUP BY MONTH(create_time)
ORDER BY create_time;

The result is as follows:

resultado do código acima

2

good morning,

Validate if this is what you want

SELECT COUNT(id) AS id, DATE_FORMAT(create_time, '%m-%Y') AS data_mes
FROM ticket
WHERE ticket_state_id = 2 AND 
    DATEDIFF(day,create_time ,GETDATE())<=365
GROUP BY MONTH(create_time);
  • 1

    Thank you so much for your help! That works too, but it’s not what I want! Fortunately I have already solved and published the correct answer to this question! Thanks again for the availability! ;D

Browser other questions tagged

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