My table contains a column of 'datetimes', with an id.
+----+---------------------+
| id | datetime |
+----+---------------------+
| 0 | 2016-09-02 12:13:13 |
| 1 | 2016-09-02 10:16:11 |
| 2 | 2016-09-05 11:03:23 |
| 3 | 2016-09-08 11:34:45 |
| 4 | 2016-09-08 09:23:06 |
| 5 | 2016-09-08 10:22:05 |
| .. | ... |
+----+---------------------+
There will be multiple instances of each date in the table. My aim is to gather the amount of times each date occurs. So for the table above:
2016-09-02 => 2
2016-09-05 => 1
2016-09-08 => 3
I then need to move the data into JSON format using PHP like so:
[{"date":"2016-09-02","count":"2"},
{"date":"2016-09-05","count":"1"},
{"date":"2016-09-08","count":"3"}]
The JSON format will be used by a d3.js script I have written to plot each date against the frequency each date occurs.
I have never dealt with this kind of query before so I really have no idea where to start, or how to use PHP to move into JSON format. Thank you to anyone that can help.
Use the following query:
SELECT DATE_FORMAT(datetime, '%Y-%m-%d') AS `date`,
COUNT(*) AS `count`
FROM yourTable
GROUP BY DATE_FORMAT(datetime, '%Y-%m-%d')
Then create the JSON in your PHP code:
$a = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$a[] = array('date' => "$row['date']", 'count' => "$row['count']");
}
$json = json_encode($a);
I think below SQL useful to you. please run and see
SELECT DATE_FORMAT(datetime, '%Y-%m-%d'),count(*)
FROM yourTable
GROUP BY 1
order by 1