我在Postgres中有一個表,用於捕獲非結構化形式的信息並重建它。我需要在從該表導出數據時重新應用一些結構,並且掙扎。在PostgreSQL中將任意多行轉換爲列
目前,我有以下形式的表:
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
,我需要產生這種形式的表格:
lbl | num | colour | percentage
----|-----|---------|------------
1 | 1 | "Red" | 25.0
2 | 2 | "Green" | 50.0
3 | 3 | "Blue" | 75.0
我已經建立了這個查詢:
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
查詢工作正常,但我需要將其擴展爲包含任意數量的名稱潛在值。我調查了crossfunc,但無法按照我的意圖使其工作。任何幫助將不勝感激。
我已經成立了一個sqlfiddle這裏是爲了幫助踢東西了:http://sqlfiddle.com/#!9/8d3133/6/0
編輯:我可以用PL/pgSQL的同時如果能夠。
我想你需要在這裏使用動態SQL。 –
「*包含任意數量的名稱*的潛在值」,這在普通SQL中是不可能的。運行查詢的數據庫_before_必須知道查詢的列數。 –
啊,好的。如果我有權訪問使用plsql可以工作嗎? – George