I have this table from fingerprint sensor and I need to show the result in one row
ID | DateTime | Flag
41 | 2017-02-22 08:05:56.000 | I
41 | 2017-02-22 18:11:03.000 | O
41 | 2017-02-23 23:45:56.000 | I
41 | 2017-02-24 08:11:03.000 | O
Result needed like this:
ID | IN-DateTime | OUT-DateTime
41 | 2017-02-22 08:05:56.000 | 2017-02-22 18:11:03.000
41 | 2017-02-23 23:45:56.000 | 2017-02-24 08:11:03.000
2
Answers
Assuming that in and out records would always be paired, we can try the following approach using
ROW_NUMBER()
:Note: The above will only work on MySQL 8+, which has the
ROW_NUMBER()
window function available.Take next event datetime for rows with flag ‘I’.
Then filter rows with flag ‘I’.
Considered IN without OUT.
See example
fiddle
More wired case:
IN without OUT and OUT without IN
fiddle