How to extract the difference of a specific column of multiple rows with same id?
Example table:
id | prev_val | new_val | date |
---|---|---|---|
1 | 0 | 1 | 2020-01-01 10:00 |
1 | 1 | 2 | 2020-01-01 11:00 |
2 | 0 | 1 | 2020-01-01 10:00 |
2 | 1 | 2 | 2020-01-02 10:00 |
expected result:
id | duration_in_hours |
---|---|
1 | 1 |
2 | 24 |
summary:
with id=1, (2020-01-01 10:00 – 2020-01-01 11:00) is 1hour;
with id=2, (2020-01-01 10:00 – 2020-01-02 10:00) is 24hour
Can we achieve this with SQL?
4
Answers
you could use min/max subqueries. For example:
Let me know if you need help in converting duration to hours.
if you need the difference between successive readings something like this should work
This solutions will be an effective way
You can use the lead()/lag() window functions to access data from the next/ previous row. You can further subtract timestamps to give an interval and extract the parts needed.
NOTE:
Your expected results, as presented, are incorrect. The results would be -1 and -24 respectively.
DATE is a very poor choice for a column name. It is both a Postgres data type (at best leads to confusion) and a SQL Standard reserved word.