Question

I have the following table:

enter image description here

Then I want to get the following:

enter image description here

I want to achieve this in postgres. What should I do?

Was it helpful?

Solution

Tabular data can be easily unpivoted with the help of JSON functions.

The query below will work, assuming tablename is replaced by your table name, and primary_key is the name of the pivot column. The other columns don't have to be specified, they're obtained automatically by json_each_text applied to row_to_json applied to all rows.

SELECT primary_key, key, value
 FROM (select row_to_json(t.*) AS line, primary_key
     FROM tablename AS t) AS r
   JOIN LATERAL json_each_text(r.line)
     ON (key <> 'primary_key')
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top