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?
How to count the number of records per day
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:How to generate daily reports for individual people
Ok this is what you really wanted. Let’s draw a sample table with some records:
To get the daily totals for a particular person, you would do:
This is selecting records where
personis John, grouped by unique days, and summing thesalesvalue for those records. If you want reports for every person combined, just remove theWHEREclause.Final note
You can simplify your SQL a little bit if you use the
DATEtype instead of theDATETIMEtype. I’m selecting and grouping by the day, month and year which I need to get using three separate functions. If you’re using theDATEtype, calling these functions would be unnecessary and I could just select and group bytsdirectly. It’s up to you how you want to represent your data.