我正在尝试将250个列的大型数据集取消。这里有一个非常好的文档解决方案unpivot and PostgreSQL.
但是,它会手动输入列名称。我想做点什么......
OR,
为noob道歉,是SQL的新手!
此数据集足以满足以下目的:
CREATE TEMP TABLE foo (id int, a text, b text, c text);
INSERT INTO foo VALUES (1, 'ant', 'cat', 'chimp'), (2, 'grape', 'mint', 'basil');
SELECT id,
unnest(array['a', 'b', 'c']) AS colname,
unnest(array[a, b, c]) AS thing
-- I would like something like.. unnest(array[column_names]) AS thing
-- where column_names = [a,b,c.. so on]
FROM foo
ORDER BY id;
预期结果:
id | colname | thing
1 | a | ant
1 | b | cat
1 | c | chimp
2 | a | grape
2 | b | mint
2 | c | basil
答案 0 :(得分:0)
使用JSONB functions,例如:
select id, key as colname, value as thing
from foo t
cross join jsonb_each_text(to_jsonb(t)- 'id')
id | colname | thing
----+---------+-------
1 | a | ant
1 | b | cat
1 | c | chimp
2 | a | grape
2 | b | mint
2 | c | basil
(6 rows)