4

I have the following data coming from Finger Print devices, Each In and Out of employees are recorded.

UserId CheckTime CheckType
------ ----------- -----------
 2 2020年08月03日 08:15:12.053 I
 2 2020年08月03日 16:00:00.053 O
 2 2020年08月04日 08:00:12.053 I
 2 2020年08月04日 16:10:00.053 O

I want the above data to be as following:

UserId CheckTime CommingTime LeavingTime
------ ----------- ----------- -------------
 2 2020年08月03日 08:15:12.053 16:00:00.053
 2 2020年08月04日 08:00:12.053 16:10:00.053

**Note: ** A user can have multiple In Out record per day

I have tried the following answers but didn't help:

How to merge multiple rows into one row with SQL?

Any idea??

asked Aug 9, 2020 at 12:55
4
  • 2
    is it possible that you may have no corresponding Out records for some In records and vice versa? what version of database server do you use? Commented Aug 9, 2020 at 15:18
  • 3
    And what happens when someone comes in before midnight but leaves after midnight? Commented Aug 9, 2020 at 15:39
  • How is this (ignoring the noted complications) not simply the minimum of the "in" rows and the maximum of the "out" rows with the appropriate group by clause? Commented Aug 9, 2020 at 18:40
  • @SMor: Seems to me like a valid option to suggest. Keep in mind that comments can't bring you rep points, but answers can (wink, wink, nudge, nudge). Commented Aug 10, 2020 at 8:52

1 Answer 1

6

Main idea:

WITH cte AS ( SELECT UserId, 
 CheckTime, 
 LEAD(CheckTime) OVER (PARTITION BY UserId ORDER BY CheckTime) NextTime, 
 CheckType, 
 LEAD(CheckType) OVER (PARTITION BY UserId ORDER BY CheckTime) NextType )
SELECT UserId, CheckTime, NextTime
FROM cte
WHERE CheckType = 'I'
 AND NextType = 'O'

Modify as you need - extract date and/or time parts, check that date parts are equal, etc.

answered Aug 9, 2020 at 18:55

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.