I have a MySQL Database That Looks like This:
Name: Joe
Items: 25
CreationDate: 2012-04-14 18:49:50
Name: John
Items: 89
CreationDate: 2012-04-14 18:47:17
Name: Bill
Items: 95
CreationDate: 2012-04-09 12:34:08
Name: Bob
Items: 35
CreationDate: 2012-04-09 12:18:23
What I want to do is group the rows by CreationDate (Based on only the day, the time at the end should not be a factor). And Then Add the Items Together to come up with an Items / Day.
So I want the output to be something like this:
2012-04-09 - 130 items
2012-04-14 - 114 items
I've tried the Group By in MySQL but I'm not sure if i'm using it right:
$sql = mysql_query("SELECT SUM(Items), CreationDate FROM People GROUP BY CreationDate ORDER BY CreationDate DESC") or die(mysql_error());
while($row = mysql_fetch_array($sql) ) {
echo '<p>' . $row['CreationDate'] . ' - ' . $row['SUM(Items)'] . '</p>';
}
That kind of works except it Groups them only on exact match Creation Date (Down to the second) and i'm not sure how to fix for that.
You need to use the date-function for the CreationDate field, such as:
SELECT SUM(Items), DATE(CreationDate) FROM People GROUP BY DATE(CreationDate) ORDER BY CreationDate DESC
A warning though: Using the DATE-function will ignore any index on the CreationDate. If the CreationDate-field is indexed, using the DATE-function and grouping on it will take much longer time.