I search a solution for my problem in SQL (postgresql).
I have a logs table with the following columns:
deviceId | id | code | timestamp |
---|---|---|---|
device1 | 1 | 12 | 1672597471000 |
device1 | 2 | 11 | 1672597471001 |
device1 | 3 | 8 | 1672597471002 |
device1 | 4 | 2 | 1672597471003 |
device1 | 5 | 9 | 1672597471004 |
device1 | 6 | 9 | 1672597471005 |
device1 | 7 | 4 | 1672597471006 |
device1 | 8 | 8 | 1672597471007 |
device1 | 9 | 9 | 1672597471008 |
device2 | 1 | 8 | 1672597471000 |
device2 | 2 | 9 | 1672597471010 |
device2 | 3 | 12 | 1672597471050 |
device2 | 4 | 8 | 1672597471100 |
device2 | 5 | 9 | 1672597471130 |
I search one query (or more) to find the time elapsed between two codes (8 and 9 for example).
The output of SQL query will be:
deviceId | elapsed time |
---|---|
device1 | 2 |
device1 | 1 |
device2 | 10 |
device2 | 30 |
I would really appreciate if anyone can suggest some ideas how to solve this problem.
I tried with lead function but i can’t reset time between each sequence (8 and 9) and ignore unique 8 or 9. In short, i’m stuck and I don’t know if it’s possible in SQL.
2
Answers
This can be accomplished by using the window function
lag()
to obtain the previous row of the current row, followed by subtraction to obtain the elapsed time between 8 and 9 using the conditionwhere code = 9 and lag_code = 8
:Result :
Demo here
Use this simple query to produce the result you need (and test it on fiddle) :
and it gives: