Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total hours worked in a day mysql

I have a MySQL table where employee login and logout timings are recorded. Here in the in-out column 1-represents login and 0-represents logout.

  [id]   [User_id]           [Date_time]                 [in_out]
    1       1          2011-01-20 09:30:03                  1
    2       1          2011-01-20 11:30:43                  0
    3       1          2011-01-20 11:45:12                  1
    4       1          2011-01-20 12:59:56                  0
    5       1          2011-01-20 13:33:11                  1
    6       1          2011-01-20 15:38:16                  0
    7       1          2011-01-20 15:46:23                  1
    8       1          2011-01-20 17:42:45                  0

Is it possible to retrieve total hours worked in a day by a user using single query?

I tried a a lot but all in vain. I can do this in PHP using array but unable to do so using single query.

like image 700
Ullas Prabhakar Avatar asked Jan 20 '11 09:01

Ullas Prabhakar


People also ask

How do you calculate total working hours by each employee from their start date in SQL?

You can use lead() and then aggregate: select employeeid, sum(timestampdiff(hour, created, next_created) as num_hours from (select t.

What is now () in MySQL?

MySQL NOW() Function The NOW() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS. uuuuuu (numeric).

Does Datepart work in MySQL?

There is no DATEPART function in MySQL. Use MONTH(date_column) or EXTRACT(MONTH FROM date_column) instead.


1 Answers

SELECT `User_id`, time(sum(`Date_time`*(1-2*`in_out`)))
  FROM `whatever_table` GROUP BY `User_id`;

The (1-2*`in_out`) term gives every login event a -1 factor and every logout event a +1 factor. The sum function takes the sum of the Date_time column, and GROUP BY `User_id` makes that the sum for each different user is created.

like image 75
Rudi Avatar answered Oct 08 '22 00:10

Rudi