I have a table in Postgres that was designed to capture information in unstructured form and rebuild it. I need to re-apply some structure when exporting data from that table and am struggling.
Currently, I have a table of the form:
lbl | name | value
----|------------|--------
1 | num | 1
1 | colour | "Red"
1 | percentage | 25.0
2 | num | 2
2 | colour | "Green"
2 | percentage | 50.0
3 | num | 3
3 | colour | "Blue"
3 | percentage | 75.0
And I need to generate a table in this form:
lbl | num | colour | percentage
----|-----|---------|------------
1 | 1 | "Red" | 25.0
2 | 2 | "Green" | 50.0
3 | 3 | "Blue" | 75.0
I have built this query:
SELECT lbl,
max(case when name = 'num' then value else '-' end) num,
max(case when name = 'colour' then value else '-' end) colour,
max(case when name = 'percentage' then value else '-' end) percentage
FROM example_table
GROUP BY lbl
The query works but I need to expand it to include an arbitrary number of potential values for name. I have investigated crossfunc but was unable to get it to work as I intended. Any help would be greatly appreciated.
I've set up an sqlfiddle here to help kick things off: http://sqlfiddle.com/#!9/8d3133/6/0
edit: I can use PL/pgSQL also if that makes it possible.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…