Skip to content
Advertisement

crosstab in PostgreSQL

I have the following tables:

and

How can I query the database so that it returns the table

where n ranges over the rows of the table sensor and ‘abbrv $i’ is replaced by the corresponding value in the table sensor?

The following query

works up to a certain extent: I need to know how many rows there are in the sensor table and I have to manually set the columns’ name.

Advertisement

Answer

I don’t have a basic answer better than yours, especially when the number of sensors/values vary per device. However, you can do something like the following :

First you can create a composite TYPE which corresponds to the list of columns with the total list of sensor.abbrv from the table sensor ordered by sensor.id :

Then you can aggregate the varying number of sensor.abbrv / reading.value pairs as json key/value pairs within a single json object per time and device_id :

RIGHT JOIN is required so that to systematically create a json key/value pair even if the json key s.abbrv doesn’t correspond to any value in the readings table.

Finally you can display the json object as a row using the jsonb_populate_record function :

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