0

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

5
  • What is your question? Commented Dec 16, 2016 at 17:21
  • see this answer stackoverflow.com/questions/1128737/unpivot-and-postgresql Commented Dec 16, 2016 at 17:25
  • I'm not sure that this solution works, forgot to add that the metrics have interdependency that is value of metric 4 depends on metric 3 and so on Not always but sometime. How to I get around that? Commented Dec 16, 2016 at 17:38
  • Possible duplicate of How to unpivot a table in PostgreSQL Commented Dec 16, 2016 at 17:48
  • another key word to search for solutions is UNPIVOT, unfortunately it doesn't appear postgresql has a nice unpivot function like some other platforms. So there are 2 main more obvious solutions, 1) union all with x# of selects 2) cross join to a tally table and large case statement. but the link I tagged also has some dynamic and json solutions that might be of interest Commented Dec 16, 2016 at 17:50

1 Answer 1

0

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.