Skip to content
Advertisement

Displaying one row with one timestamp and a corresponding x-integer array as x rows with x timestamps and one corresponding integer

Apologies for the poorly worded question, I don’t know how to succinctly describe my problem. I am working with data from a sensor that scans a room every 10 minutes to see how many people are in it. The data looks something like this

reading_id |      timestamp      |    values      |          
--------------------------------------------------
1          | 2019-02-28 01:00:00 | {1,1,6,17,4,4} |
2          | 2019-02-28 02:00:00 | {3,4,6,3,0,8}  |
3          | 2019-02-28 03:00:00 | {0,0,0,0,0,0}  |

Is there any way I can have it look like this?

reading_id |      timestamp      |    values      |
-------------------------------------------------- 
1          | 2019-02-28 01:00:00 | 1              |
1          | 2019-02-28 01:10:00 | 1              |
1          | 2019-02-28 01:20:00 | 6              |
1          | 2019-02-28 01:30:00 | 17             |
1          | 2019-02-28 01:40:00 | 4              |
1          | 2019-02-28 01:50:00 | 4              |
2          | 2019-02-28 02:00:00 | 3              |
...

I’m not sure what would happen to the reading_id but I do not need it regardless.

Advertisement

Answer

You can use unnest with ordinality to get the index of each array element and use that to add the 10 minute intervals.

select t.reading_id,
       t."timestamp" + interval '10 minutes' * (u.idx - 1) AS timestamp,
       u.value
from the_table t
   cross join unnest(t."values") with ordinality AS u(value, idx)
order by 1,2;

Online example: https://rextester.com/TEB87353

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