Skip to content
Advertisement

MySQL query to get last 12 months data grouped by month including zero counts

I have table orders (order_id, order_processed_date). I want the count of orders per month for last 12 months. If any month has 0 orders, then it should print 0.

Something like this:

I already searched in this website and get some queries but did not find exact solution for this. I get result using below query but it does not have year:

Can please someone help me to give me result as I required.

Advertisement

Answer

The following query builds a list of 1st day of month for previous 12 months. For example on Oct 19 2018 the list will contain dates from Oct 01 2018 to Nov 01 2017. Left join does the rest:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement