Skip to content
Advertisement

Postgres Get column name and value as rows for given ID

I have a table like this

CREATE TABLE measurement (
 city_id int not null PRIMARY KEY,
 logdate date not null,
 peaktemp int,
 unitsales int
)

I need to get values for a given ID like this

select * from measurement where city_id ='1';

Name     |Value
---------|----------
city_id  |1
logdate  |2006-02-02
peaktemp |1
unitsales|1

is There any simple way to achieve this.

Advertisement

Answer

You could convert the row to a json & then use json_each to transpose the data as you desire:

SELECT
  kv.key
, kv.value

FROM measurement 
   , json_each(row_to_json(measurement.*)) kv

WHERE city_id = 1
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement