I have a table that contains event data for N number of devices, each of which may or may not be adding data to the table at a given time. I need to query the table for the last status of each distinct device in table, as well as the prior status of the device.
Example table data:
id | device | event_data | date_time
________________________________________________
1019 | sensor501 | open | 2018-01-05T00:05:15Z
1020 | sensor509 | closed | 2018-01-05T00:05:16Z
1021 | sensor501 | reset | 2018-01-05T00:05:18Z
1022 | sensor501 | closed | 2018-01-05T00:05:19Z
1023 | sensor974 | open | 2018-01-05T00:05:27Z
1024 | sensor729 | closed | 2018-01-05T00:06:07Z
1025 | sensor729 | reset | 2018-01-05T00:06:46Z
Example result data:
device | event_data | prev_event_data | date_time
________________________________________________
sensor501 | closed | reset | 2018-01-05T00:05:19Z
sensor509 | closed | null | 2018-01-05T00:05:16Z
sensor974 | open | null | 2018-01-05T00:05:27Z
sensor729 | reset | closed | 2018-01-05T00:06:46Z
How would you, in the most efficient way, query the example table to get the example result data?
See Question&Answers more detail:os