1741. Find Total Time Spent by Each Employee
Description
Table: Employees
+++  Column Name  Type  +++  emp_id  int   event_day  date   in_time  int   out_time  int  +++ (emp_id, event_day, in_time) is the primary key (combinations of columns with unique values) of this table. The table shows the employees' entries and exits in an office. event_day is the day at which this event happened, in_time is the minute at which the employee entered the office, and out_time is the minute at which they left the office. in_time and out_time are between 1 and 1440. It is guaranteed that no two events on the same day intersect in time, and in_time < out_time.
Write a solution to calculate the total time in minutes spent by each employee on each day at the office. Note that within one day, an employee can enter and leave more than once. The time spent in the office for a single entry is out_time  in_time
.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input: Employees table: +++++  emp_id  event_day  in_time  out_time  +++++  1  20201128  4  32   1  20201128  55  200   1  20201203  1  42   2  20201128  3  33   2  20201209  47  74  +++++ Output: ++++  day  emp_id  total_time  ++++  20201128  1  173   20201128  2  30   20201203  1  41   20201209  2  27  ++++ Explanation: Employee 1 has three events: two on day 20201128 with a total of (32  4) + (200  55) = 173, and one on day 20201203 with a total of (42  1) = 41. Employee 2 has two events: one on day 20201128 with a total of (33  3) = 30, and one on day 20201209 with a total of (74  47) = 27.
Solutions
Solution 1: Group By + Sum Function
We can first group by emp_id
and event_day
, and then calculate the total time for each group. The total time is equal to the sum of the differences between out_time
and in_time
for each record in the group.
SQL Code

