I have an activity table that looks like this:
activity_id int
activity_client_id int
activity_type_id int
activity_start_date datetime
activity_end_date datetime
One record for each instance of a client performing an activity.
For example, today they may have an activity record that has an activity_start_date of
'03-JUN-2015 09:00:00' and an activity_end_date of
'03-JUN-2015 11:30:00'
So using this table, we can total up how many minutes activity an client has performed by doing this:
select client_id,
sum(DATEDIFF(MINUTE, activity_start_date , activity_end_date)) as total_minutes
from activity
group by client_id
Here's the tricky bit : I need to run a query that will show the date that each client reached a total of 300 minutes activity.
I am considering a creating a stored procedure that loops through each client, keeping a running count of the activity minutes. When it reaches 300 minutes, the procedure updates a column on another table, recording the date.
However, I'm wondering if I can achieve the results on the fly with a select query instead of having to run the stored procedure ?
Edit: As requested, I will give you some sample data to clarify what I am trying to achieve. Below we can see the records for client_id 112. The question is, on what date did the client complete 300 minutes (5 hours) of total activity ? For this client the answer would be 03/06/2015
+-------------+----------------------+---------------------+-------------------+
| activity_id | activity_client_id | activity_start_date | activity_end_date |
+-------------+----------------------+---------------------+-------------------+
| 112434 | 112 | 01/06/2015 09:00 | 01/06/2015 11:00 |
| 112490 | 112 | 02/06/2015 12:00 | 02/06/2015 16:00 |
| 112688 | 112 | 03/06/2015 09:00 | 03/06/2015 16:00 |
| 112998 | 112 | 04/06/2015 09:00 | 04/06/2015 10:00 |
+-------------+----------------------+---------------------+-------------------+
So using a select statement, how could we have worked this out ? I can work out how to do this in a stored procedure, using a loop, but I would prefer to just have a select statement.