PostgreSQL列到没有明确指定列名/列的行 [英] PostgreSQL columns to rows with no explicilty specifying column names / columns
问题描述
我想知道有什么方法可以在PostgreSQL中取消透视(将列转换为行)数据。
例如,如果我有一个像这样的表:
ID名称年龄
1爱丽丝16
2鲍勃21
3卡尔18
我想获得类似
<$ p $的输出p>
ID Column_Name Column_Value
1名称Alice
1年龄16
2名称Bob
2年龄21
3名称Carl
3年龄18
我知道我可以这样做( sql小提琴 并尝试使用数据):
选择
U.ID,
unnest(array ['Name','Age'])作为Column_Name,
unnest(array [U .Name,U.Age :: text])作为用户的Column_Value
作为U
但是有什么办法可以对表w中的所有列执行此操作吗?是否没有明确指定列名?
例如,对于SQL Server,我知道至少有两种方法可以执行此操作-动态SQL或将数据转换为xml并解析xml- SQL Server:从列到行。
使用 hstore
扩展名:
SELECT id,skeys(hstore(users))AS列,svals(hstore(users))AS值FROM用户;
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;
这篇关于PostgreSQL列到没有明确指定列名/列的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!