按用户标识为状态系统组生成报告,状态为

时间:2015-10-29 14:39:01

标签: sql database

我有员工出勤系统的下表

userid  CheckTime               CheckType
1       2015-07-31 14:29:18.000     I   
1       2015-07-31 18:29:18.000     O   
1       2015-08-01 08:12:45.000     I   
1       2015-08-02 03:19:03.000     O   
1       2015-08-02 08:15:23.000     I   
1       2015-08-02 14:05:52.000     O   
1       2015-08-02 19:48:57.000     I   
1       2015-08-02 21:48:57.000     O

如何获得结果如下

userid    checkinTime             CheckOuttime

1         2015-07-31 14:29:18.000 2015-07-31 18:29:18.000
.
.
1         2015-08-01 08:12:45.000 2015-08-02 03:19:03.000   

1 个答案:

答案 0 :(得分:0)

You are likely looking for something like this:

Select UserId, Min(CheckTime) As CheckInTime, Max(CheckTime) As CheckOutTime
From EmployeeAttendance
Group By UserId, Cast(CheckTime As Date);

Update 2015-11-02

For the special case you mentioned, below is a more robust query...

Select UserId, InTime.CheckTime As CheckInTime, Min(OutTime.CheckTime) As CheckOutTime
From 
    (Select UserId, CheckTime From EmployeeAttendance Where CheckType = 'I') As InTime
    Left Join 
    (Select UserId, CheckTime From EmployeeAttendance Where CheckType = 'O') As OutTime
    On InTime.UserId = OutTime.UserId
    And InTime.CheckTime < OutTime.CheckTime
Group By UserId, InTime.CheckTime;

This query will pick the first checkout time that occurs after each checkin time.

You could take this query a step further by presenting a CheckOutTime of null when there are two consecutive check ins. It really depends on how you will use this data and how much you trust the data.