Problem in getting records from last 13 months in MySQL

Sachin :

I am working on to get records from last 13 months using following MySQL query:

SELECT YEAR(`customer_date`),
       MONTHNAME(`customer_date`),
       COUNT(`customer_date`) AS Enquiries
FROM   `crm_customers`
WHERE  DATE(`customer_date`) BETWEEN CURRENT_DATE - INTERVAL 13 month AND
                                     CURRENT_DATE
GROUP  BY YEAR(`customer_date`),
          MONTH(`customer_date`)
ORDER  BY YEAR(`customer_date`) DESC,
          MONTH(`customer_date`) DESC  

My prototype MySQL table crm_customers looks as:

customer_id    customer_date
1              2019-02-01 00:00:00
2              2019-02-02 00:00:00
...            ...
...            ...
...            ...

Output:

enter image description here

Though above query does work fine and gives me almost correct result set except one issue related to very last month of the last year from a gap of 13 months from today.

Today is 7th of March 2020. The date condition in my above query

WHERE  DATE(`customer_date`) BETWEEN CURRENT_DATE - INTERVAL 13 month AND CURRENT_DATE

starts fetching the result from 7th of Feb 2019.

In the month of Feb, 2019 I have 104 entries. But my above SQL fetches only 80 entries because 24 entries are before 07-Feb-2019 (between 1 Feb and 6 Feb 2019). I want to include those entries as well. How can I modify my date condition to achieve the required result.

syrkull :

change your WHERE clause to:

WHERE  DATE(`customer_date`) BETWEEN DATE_FORMAT(NOW() ,'%Y-%m-01') - INTERVAL 13 month AND DATE_FORMAT(NOW() ,'%Y-%m-01')

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=33107&siteId=1