1
+-------------+---------------------+
| uid         | date                |
+-------------+---------------------+
|          35 | 01-11-2009 19:32:44 | 
|          35 | 01-13-2009 22:33:49 | 
|          42 | 01-23-2009 22:08:24 | 
|          42 | 02-01-2009 22:33:57 | 
|          35 | 02-01-2009 22:37:34 | 
|          35 | 04-20-2009 15:23:49 | 
+-------------+---------------------+

I want to get a count for each day for a specific uid like and display the empty days (within a range):

User 35 (21 days)
01-11-2009 -> 1
01-12-2009 -> 0
01-13-2009 -> 1
01-14-2009 -> 0
01-15-2009 -> 0
01-16-2009 -> 0
01-17-2009 -> 0
01-18-2009 -> 0
01-19-2009 -> 0
01-20-2009 -> 0
01-21-2009 -> 0
01-22-2009 -> 0
01-23-2009 -> 0
01-24-2009 -> 0
01-25-2009 -> 0
01-26-2009 -> 0
01-27-2009 -> 0
01-28-2009 -> 0
01-29-2009 -> 0
01-30-2009 -> 0
01-31-2009 -> 0
02-01-2009 -> 1

So far I got

SELECT MONTHNAME(date), COUNT(uid) FROM cliques_referidos WHERE uid = 35 GROUP BY YEAR(date), MONTH(date), DAY(date)

How to get the 0 count for the days in between?

andrepcg
  • 1,301
  • 7
  • 26
  • 45

1 Answers1

2

Assuming it's an option, consider creating a Dates Lookup table. Then you can easily use an OUTER JOIN to create your list. Here is an SO post about it.

Calling the lookup table datelookup with a date field called datevalue, then this should work:

SELECT MONTHNAME(d.datevalue), COUNT(cr.uid) 
FROM datelookup d LEFT JOIN
    cliques_referidos cr ON d.datevalue = DATE(cr.date)
        and cr.uid = 35 
GROUP BY YEAR(d.datevalue), MONTH(d.datevalue), DAY(d.datevalue)

Since you're date field is a datetime, use DATE() in your join.

If you can't create a lookup table, look into using a stored procedure or a function since MySQL doesn't support Recursive CTEs. Search SO for some examples.

Community
  • 1
  • 1
sgeddes
  • 62,311
  • 6
  • 61
  • 83