Postgres:根据行值选择列

时间:2018-11-21 16:23:15

标签: postgresql

我有2张桌子:

表A

 Section | measure_name   |
---------+----------------|
 A       |      col1      |
 B       |      col2      |
 C       |      col3      |

表B

 Facility | col1| col2| col3| 
----------+-----+-----+-----+
 NY       |  5  | 50  |  90 |

我想写一个查询,从measure_name中选择Table A中的Table B

1 个答案:

答案 0 :(得分:2)

似乎您希望从表B中获取与每个measure_name对应的列的值

如果是,则使用UNNEST()将表B转换为行,然后将其与表A联接。

with c AS
( SELECT 
       unnest(array['col1', 'col2', 'col3']) AS colname,
       unnest(array[col1, col2, col3]) AS value
FROM B
) 
SELECT a.*,c.value FROM A 
JOIN C ON a.measure_name = c.colname;

这给你

Section measure_name value
A       col1          5
B       col2         50
C       col3         90

Demo