Skip to content
Advertisement

Compare previous row’s date in grouped query [closed]

I calculate hours that the air temperature below 7.22. I want to do this calculation on the SQL side.

I have the following table

Data’s date interval can be anything.

What I want to get

Rules

  • if there isn’t a previous row, we take this as 1 hour.

  • if there is; we take the difference of two dates. BUT if it’s higher than 1 hour, we take this as 1 hour.

How 2020-12-02’s value is 3.083?

If I get the previous value’s date, I can compare and calculate but I don’t know how can I get previous row while using group by.

I thought something like this but I am not sure how can apply rules above.

EDIT: dbfiddle

Advertisement

Answer

You can use LEAD() to get the next created_at. Then use arithmetic to limit the difference to 60:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement