If I have records in a table that are timestamped how do I query so that I get the results for each day for each user as a row in the resultset along with additional info from another table?
Example:
batch_log
id | userid | batchid | start_time | end_time |time_elapsed
----------------------------------------------------------------------------------
1 | bob | 123sgd |2011-06-23 18:00:00 | 2011-06-23 18:12:00 | 00:12:00
2 | jim | 234sgd |2011-06-22 12:00:00 | 2011-06-22 12:12:00 | 00:12:00
3 | bob | 1234gd |2011-06-23 19:00:00 | 2011-06-23 19:08:00 | 00:08:00
4 | bob | 1Abeds |2011-06-22 19:00:00 | 2011-06-23 20:24:00 | 00:24:00
screwups
id | userid | time_of_screwup
---------------------------------------------
1 | bob |2011-06-23 19:29:16
2 | jim |2011-06-23 16:29:24
3 | bob |2011-06-22 12:29:16
4 | bob |2011-06-23 13:29:16
How do I select so that I can get both the time elapsed and the number of screwups daily for each person so that I can feed this into excel.
Example output:
userid | date |COUNT(time_elapsed)| COUNT(screwups)|
------------------------------------------------------------
bob | 2011-06-23 | 00:20:00 | 2
jim | 2011-06-22 | 00:12:00 | 1
bob | 2011-06-22 | 00:24:00 | 1
EDIT: Data that makes more sense
Having an
idfield on your results doesn’t really make sense, so I’ll just ignore that that field exists. Similarly, I doubt thattime_elapsedwill be the same for different job runs on the same day, so we’ll knock that out.Getting rid of those two fields leaves us with a fairly straightforward
GROUP BYquery. I don’t know the specifics of your database so, for the purposes of this problem, I’ll assume that your DB has aDATE()function that returns the date part of a timestamp. Unless you left out important details in your question , the existence of thebatch_logtable is a red herring. You really just want toSELECT userid, DATE(time_of_screwup), count(*) FROM screwups GROUP BY userid, DATE(time_of_screwup).