문제

I would like to know is there any way to do unpivot (turn columns to rows) data in PostgreSQL.

For example, if I have a table like:

ID   Name    Age
1    Alice    16
2    Bob      21
3    Carl     18

I want to get an output like

ID   Column_Name Column_Value
1    Name        Alice
1    Age         16
2    Name        Bob
2    Age         21
3    Name        Carl
3    Age         18

I know I could do it like (sql fiddle with data to try it):

select
   U.ID,
   unnest(array['Name', 'Age']) as Column_Name,
   unnest(array[U.Name, U.Age::text]) as Column_Value
from Users as U

But is there any way I could do it for all columns in table without explicitly specifying column names? For example, for SQL Server I know of at least 2 ways to do it - dynamic SQL or turn data into xml and parse xml - SQL Server : Columns to Rows. May be there's some xml trick in PostgreSQL too?

도움이 되었습니까?

해결책

With hstore extension:

SELECT id, skeys(hstore(users)) AS column, svals(hstore(users)) AS value FROM users;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top