Sql 如何将数据列转换为单个列,其中每行数据垂直堆叠在该列中(在Postgres中)?
我们有这样的横向数据表示:Sql 如何将数据列转换为单个列,其中每行数据垂直堆叠在该列中(在Postgres中)?,sql,postgresql,unpivot,Sql,Postgresql,Unpivot,我们有这样的横向数据表示: |id|col1|col2|col3|col4|col5| |01|1111|2222|3333|4444|5555| |02|1234|5678|9012|3456|7890| ... 我想将其转换为: |id|col|col_data| |01| 1| 1111| |01| 2| 2222| |01| 3| 3333| |01| 4| 4444| |01| 5| 5555| |02| 1| 1234| |02|
|id|col1|col2|col3|col4|col5|
|01|1111|2222|3333|4444|5555|
|02|1234|5678|9012|3456|7890|
...
我想将其转换为:
|id|col|col_data|
|01| 1| 1111|
|01| 2| 2222|
|01| 3| 3333|
|01| 4| 4444|
|01| 5| 5555|
|02| 1| 1234|
|02| 2| 5678|
|02| 3| 9012|
|02| 4| 3456|
|02| 5| 7890|
....
我能够使用以下命令正确列出目标表的|id | col |
列:
SELECT
id,
unnest((
select
array_agg(split_part(column_name::text, 'l', 2)::numeric)
FROM INFORMATION_SCHEMA.columns
WHERE
TABLE_NAME = 'my_table' and
TABLE_SCHEMA = 'my_schema'
)) AS "col"
FROM my_schema.my_table
group by "col" id
ORDER BY id, "col";
但我不知道如何以所需的格式从源表中获取数据
供参考:
- 我没有超级用户权限
- 实际表有26列
select t.id, up.*
from the_table t
cross join lateral (
values (1, col1), (2, col2), (3, col3), (4, col4), (5, col5)
) as up(col, col_data);
如果您不关心所有内容都转换为文本(而不是保留原始数据类型),则可以使用JSON取消填充列:
select t.id,
up.col,
up.col_data
from the_table t
cross join jsonb_each_text(to_jsonb(t) - 'id') as up(col, col_data)