Skip to content
Advertisement

Calculate interval between boolean column change

I have a table with measurements of weather here is a simplified version of it:

and I need to calculate how much time is been sunny. I know I need to use window functions but I’m stuck. Because I need this interval to be calculated in some range for example for last day. I have been able to make a query to this stage.

this query results in to:

but if the first lane of this result is rainy = False the start_date should be the same as one in query 2020-01-30T00:00:00.000Z (I’m assuming that if it’s sunny on the first result it has been sunny for whole time between my range start and this first recorded measurement) and also there is missing the last row because last measured state is sunny. So started_at for this last row should be 2020-01-31 18:44:35.08+00 and end_at should be NOW().

Can somebody please help me?

I’m using postgresql 12.1.

Advertisement

Answer

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