在 postgresql 查询中需要拆分行的帮助
need help on split row in postgresql query
我有以下 table,我需要按 role_collection 值拆分行:
name role_collection date
------------------------------------
raj 3,5 2018 6 12
gopi 2,3,6 2018 6 12
mani 3,4,5,7 2018 6 12
现在我需要这样的输出:
name role date
------------------------
raj 3 2018 6 12
raj 5 2018 6 12
gopi 2 2018 6 12
gopi 3 2018 6 12
gopi 6 2018 6 12
mani 3 2018 6 12
mani 4 2018 6 12
mani 5 2018 6 12
mani 7 2018 6 12
欢迎使用 Whosebug。
假设您有以下 table 结构:
CREATE TABLE t (name TEXT, role_collection TEXT, d DATE);
您的示例数据:
INSERT INTO t VALUES ('raj','3,5','2018-6-12'),
('gopi','2,3,6','2018-6-12'),
('raj','3,4,5,7','2018-6-12');
使用逗号分隔 role_collection 值创建一个数组 STRING_TO_ARRAY
- in case the column role_collection
ins't already of type TEXT[]
or VARCHAR[]
. Then using UNNEST
您可以提取该数组的所有元素,如下所示:
SELECT name, UNNEST(STRING_TO_ARRAY(role_collection,',')),d
FROM t;
name | unnest | d
------+--------+------------
raj | 3 | 2018-06-12
raj | 5 | 2018-06-12
gopi | 2 | 2018-06-12
gopi | 3 | 2018-06-12
gopi | 6 | 2018-06-12
raj | 3 | 2018-06-12
raj | 4 | 2018-06-12
raj | 5 | 2018-06-12
raj | 7 | 2018-06-12
(9 Zeilen)