Reputation: 40643
Assume I have a log of something. Each record has a timestamp (MySQL data type TIMESTAMP) in the format date('Y-m-d H:i:s')
(from PHP). I need to produce a report that looks like this:
===========================================
| Date | Total Sales |
===========================================
| Thursday, Dec 1, 2011 | 100 |
-------------------------------------------
| Friday, Dec 2, 2011 | 200 |
-------------------------------------------
| Saturday, Dec 3, 2011 | 150 |
-------------------------------------------
... and so on ...
I assume I have to dynamically build the SQL from PHP, which is OK. I'm just not sure what the SQL would look like. Ideas?
Upvotes: 2
Views: 8140
Reputation: 2674
This is what I originally thought you wanted. I'm leaving it here because it might be useful to other people.
You have a bunch of timestamps. You want to group them by individual days and get the number of records per day.
Assuming your timestamp field is named ts
, you can do something like this:
SELECT COUNT(*), DAY(ts), MONTH(ts), YEAR(ts) FROM tableName
GROUP BY YEAR(ts), MONTH(ts), DAY(ts);
Ok this is what you really wanted. Let's draw a sample table with some records:
ts person sales
2011-12-01 10:00:00 John 10
2011-12-01 10:30:00 Mary 25
2011-12-01 11:00:00 John 20
2011-12-02 14:00:00 John 40
To get the daily totals for a particular person, you would do:
SELECT SUM(sales), DAY(ts), MONTH(ts), YEAR(ts) FROM tableName
WHERE person='John'
GROUP BY YEAR(ts), MONTH(ts), DAY(ts);
This is selecting records where person
is John, grouped by unique days, and summing the sales
value for those records. If you want reports for every person combined, just remove the WHERE
clause.
You can simplify your SQL a little bit if you use the DATE
type instead of the DATETIME
type. I'm selecting and grouping by the day, month and year which I need to get using three separate functions. If you're using the DATE
type, calling these functions would be unnecessary and I could just select and group by ts
directly. It's up to you how you want to represent your data.
Upvotes: 9