0

I have the following query:

select date(updated_at) as data, COUNT(id) as numar 
from `coupons`
where `user_id` = 5 and `won_by` != 0 and `updated_at` >= '2016-04-01'
group by DAY(updated_at), month(updated_at), year(updated_at)

and the result is this:

2016-04-01-   229
2016-04-03-   30
2016-04-04-   6
2016-04-07-   1
2016-04-08-   1
2016-04-10-   1

What can I do to receive something like this:

2016-04-01-   229
2016-04-02-   0
2016-04-03-   30
2016-04-04-   6
2016-04-05-   0
2016-04-06-   0
2016-04-07-   1
2016-04-08-   1
2016-04-10-   1
1
  • Why don't you GROUP BY date(updated_at)? Commented Apr 11, 2016 at 20:39

1 Answer 1

2

The best way that I've found to do this is to simply create (and maintain) a secondary table with a single column, containing all of the dates that you care about. Something like:

CREATE TABLE date_join ( date date not null primary key );

Then insert records for each date in whatever way is convenient (by hand, if it's a one-off, as part of your daily process, via stored procedure, etc).

At that point, it's simply a left join of date_join and your initial query, with a CASE statement to translate NULLs to 0s:

SELECT dj.date, q.numar
  FROM      date_join dj
  LEFT JOIN (select date(updated_at) as date, COUNT(id) as numar 
               from `coupons`
              where `user_id` = 5 and `won_by` != 0 and `updated_at` >= '2016-04-01'
              group by DATE(updated_at)
            ) q
         ON dj.date = q.date
   ORDER BY dj.date;
Sign up to request clarification or add additional context in comments.

1 Comment

A table with 100K dates (200+ years) will consume about 2.5MB in MySQL. No need to ever maintain it in your life :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.