Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何将数据列转换为单个列,其中每行数据垂直堆叠在该列中(在Postgres中)?_Sql_Postgresql_Unpivot - Fatal编程技术网

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)