Unnesting in PostgreSql

69 views Asked by At

I have a table that has 30 columns and it keeps growing. I cannot break it into multiple tables as it causes some visualization issues on Tableau. So the solution I was looking at was to create a new table. The old looks like

id | name | city| country| metric1 | metric2|.....|metric30  
------------------------------------------------------------
1  | dgshfsshd| Bost |United Stats|sjdhsjdsjdhjs|gdshduadjd|.......|hdhsjfhsjfsjf
2  | jsghfghfg| gert |United Stats|sjdhsjdsjdhjs|gdshduadjd|.......|hdhsjfhsjfsjf
.  
.  
.  

The new table format should be something like not sure if it will work (I'm open to new ideas as well)

id | name | city| country | metric name | metric value  
1  |dgfdhh| sjdh|sghshdjd|metric1|sjdsjhfsfhsjfhsjf  
2  |jagdha| qewt|shgshfgs|metric2|hfjshfjhsjfshjsfh  
.  
.  
.  

Let me know if you have any more questions. I am using postgres

1

There are 1 answers

0
AudioBubble On

You can unnest an array of those columns and use with ordinality to get the index of the column in the array

select t.id, t..name, t.city, t.country, 
       concat('metric', m.idx) as metric_name, 
       m.val as metric_value
from the_table t
  cross join lateral unnest(array[metric1,metric2,.....,metric30) with ordinality as m(val,idx);