From a database, I’m trying to find profiles that have been updated in the last X days and group them based on date.
My SQL structure looks like this:
id (int)
date_modified (date)
which produces a result something like this:
+----+---------------+
| id | date_modified |
+----+---------------+
| 86 | 2012-06-22 |
| 87 | 2012-06-22 |
| 88 | 2012-06-22 |
| 89 | 2012-06-22 |
| 63 | 2011-10-31 |
| 72 | 2012-02-06 |
| 60 | 2011-10-17 |
| 71 | 2012-02-29 |
| 69 | 2011-11-18 |
| 76 | 2012-02-29 |
| 70 | 2011-11-18 |
| 75 | 2012-02-29 |
| 73 | 2012-02-06 |
| 74 | 2012-02-28 |
| 77 | 2012-02-29 |
| 80 | 2012-05-07 |
| 82 | 2012-06-12 |
| 83 | 2012-08-15 |
| 84 | 2012-09-07 |
| 85 | 2012-08-15 |
+----+---------------+
Ideally, I would want to work the query so it produces a result like this:
+-------+----------+
| total | days_ago |
+-------+----------+
| 4 | 1 |
| 6 | 2 |
| 8 | 3 |
| 12 | 7 |
| 3 | 30 |
| 55 | 90 |
| 28 | 180 |
| 37 | 270 |
| 42 | 360 |
+----+-------------+
Where it’s converting the date_modified to a number of days ago and grouping it in the increments shown above.
I’m assuming this would be possible using cases in the select query, but I’m a bit at a loss for how to go about doing it.
You need to use the DATEDIFF MySQL function:
In your case, it’s simply solved by using