Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sum total time between two date columns for all records, grouped by other columns

I have the following table structure:

id user_id action_type action_start_time action_end_time
1 5 4 2023-06-21 16:52:49.111 2023-06-21 16:55:49.022
2 3 6 2023-06-21 16:55:51.052 2023-06-21 17:10:19.100
3 5 4 2023-06-21 18:38:44.062 2023-06-21 18:59:51.025
4 16 1 2023-06-21 19:52:39.426 2023-06-21 20:01:49.127
5 5 1 2023-06-21 20:11:19.321 2023-06-21 21:55:49.132

And I need to calculate the total time each user spent per action_type.

I only managed to work with DATEDIFF to sum the number of seconds per row:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT DATEDIFF(SECOND, action_start_time, action_end_time) AS TotalSeconds from my_table;

But I was not sure about how to group by each user id and action type.

>Solution :

I was not sure about how to group by each user id and action type

You simply do almost exactly what you say and group by those columns:

select user_id, action_type, 
  sum(DateDiff(second, action_start_time, action_end_time)) as TotalSeconds 
from my_table
group by user_id, action_type;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading