【发布时间】:2016-12-21 12:40:40
【问题描述】:
我有一张表格,里面有这样的数据:
select * from data
id | col1 | col2 | col3
---+-------+-------+-------
1 | 1,2,3 | 4,5,6 | 7,8,9
我想得到这样的数据:
id | name | dd | fn | suf
---+------+----+----+-----
1 | col1 | 1 | 2 | 3
1 | col2 | 4 | 5 | 6
1 | col3 | 7 | 8 | 9
目前,我在这样的查询中使用split_part():
SELECT * from(
select id,
'col1' as name,
NULLIF(split_part(col1, ',', 1), '') AS dd,
NULLIF(split_part(col1, ',', 2), '') AS fn,
NULLIF(split_part(col1, ',', 3), '') AS suf
from data
UNION
select id,
'col2' as name,
NULLIF(split_part(col2, ',', 1), '') AS dd,
NULLIF(split_part(col2, ',', 2), '') AS fn,
NULLIF(split_part(col2, ',', 3), '') AS suf
from data
UNION
select id,
'col3' as name,
NULLIF(split_part(col3, ',', 1), '') AS dd,
NULLIF(split_part(col3, ',', 2), '') AS fn,
NULLIF(split_part(col3, ',', 3), '') AS suf
from data
);
有没有更优雅的方式? 我有 20 列。
【问题讨论】:
-
你应该使用 Postgres 函数
split_part()。 -
看我的要求。
-
您的表定义和 Postgres 版本会有所帮助。
col1、col2、col3的数据类型是text?或int[]?元素是整数值?最多3个元素?可以有 0 个元素(空字符串/数组)吗?想要的结果?缺少的元素会产生 NULL 值吗?
标签: sql postgresql split pivot delimiter