I have an application that logs three states of some machine. I need to report how long the machine stayed in each state from 00:00:00 until 23:59:59 for each day.
I need a help to build a postgresql query to get entire time interval that some event occur during the day.
For example, as you can see below the data are shown between 23:50:00 previous day until 01:00:00 follwing day.
| device_id varchar(50) | Value int4 | Date_time timestamptz |
|---|---|---|
| device1 | 0 | 2022-23-04 23:50:00 |
| device1 | 0 | 2022-24-04 00:10:00 |
| device1 | 0 | 2022-24-04 00:15:00 |
| device1 | 0 | 2022-24-04 00:20:00 |
| device1 | 1 | 2022-24-04 00:25:00 |
| device1 | 1 | 2022-24-04 00:30:00 |
| device1 | 1 | 2022-24-04 11:00:00 |
| device1 | 0 | 2022-24-04 21:00:00 |
| device1 | 1 | 2022-25-04 01:00:00 |
I am calculating the duration between state changes and I am also inserting in the table and I am simply making the sum but it is giving me the following result:
Total:
- State = 0 - 04:35
- State = 1 - 20:35
- Sum Both = 25:10:00
The query I need should not consider the portion of time that belong to other days that is not 24/04/2021 and must give me:
Total Day 24/04/2022:
- State = 0 - 03:25
- State = 1 - 20:35
- Sum Both = 24:00:00
And in the and of each day I need to have the percentage of time the machine stayed in each state and build a pie chart.
Is there a way to make a query that fits this needs?
Thank You all in advance for the help.
@shawnt00 answer worked. Now I am trying to figure out how to organize the data so the query result come as the following:
| device_id | state_0 | state_1 | state_9 |
|---|---|---|---|
| device_id | timespan_state_0 | timespan_state_1 | timespan_state_9 |
For the given example, should be as shown below, I added an second device just to augment the example :)
| device_id | state_0 | state_1 | state_9 |
|---|---|---|---|
| device1 | 03:25 | 20:35 | 00:00 |
| device2 | X | Y | Z |
Att.
Winner Martins