1

I need to return the count of item sold in last 30 days and return 0 if there is no item sold. My current query is working well for getting days where there is item sold but it is not returning 0 values and I need it.

Here is my current query

SELECT DATE_FORMAT(FROM_UNIXTIME(purchase_date), '%m/%d') AS Dates, COUNT(*) AS COUNT 
FROM purchases
WHERE FROM_UNIXTIME(purchase_date) BETWEEN NOW() - INTERVAL 30 DAY AND NOW()
GROUP BY Dates
ORDER BY Dates ASC

The actual result are:

02/15 -> 10
02/16 -> 12
02/18 -> 22

But I'm missing the empty date(s) that I want to return as 0.

This is the table structure:

userid int(11), purchase_item int(11), purchase_date int(11)
FanoFN
  • 6,815
  • 2
  • 13
  • 33
Mireille28
  • 337
  • 5
  • 13

1 Answers1

3

You can generate the last 30 days using a recursive CTE:

with recursive dates as (
      select curdate() as dte, 1 as n
      union all
      select dte - interval 1 day, n + 1
      from dates
      where n < 30
     ) 

The rest is just incorporating this into a query using a LEFT JOIN or correlate subquery:

with recursive dates as (
      select curdate() as dte, 1 as n
      union all
      select dte - interval 1 day, n + 1
      from dates
      where n < 30
     ) 
select d.dte, count(p.purchase_date)
from dates d left join
     purchases p
     on from_unixtime(purchase_date) >= d.dte and
        from_unixtime(purchase_date) < d.dte + interval 1 day
group by d.dte;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786