-- 將逗號分隔的字符串轉為多行
SELECT unnest(string_to_array('4513,4564,555',',')) as a1;
-- array轉為行
SELECT unnest(ARRAY[1,2]);
SELECT * from unnest(ARRAY[1,2],ARRAY['foo','bar','baz']);
補充:PostgreSQL 行轉列、列轉行字符串函數(shù)、字符串分割函數(shù)
本文主要介紹PostgreSQL 的行轉列、列轉行以及字符串切割函數(shù),實際業(yè)務中對前兩個均有使用,并配有實際例子參考。
1、字符串列轉行
string_agg,某些地方也稱為字符串聚合操作。
如果需要按照一個字符串按照某個分割符拼接起來。
例如:

按照id把字符串按照指定分隔符拼接起來。實際業(yè)務中有什么需要這種字符串函數(shù)的呢?

-----------------------update 2020年1月16日17:05:59-----------------------
這里學習一個和系統(tǒng)表有關的查詢,用到了stragg ,用法之妙,自己體會。
SELECT string_agg(att.attname,',' order by attrnums) as distribution
FROM gp_distribution_policy a,pg_attribute att
WHERE a.localoid ='sor.wpp_adefect_f_n'::regclass
and a.localoid = att.attrelid
and att.attnum = any(a.attrnums);
select attname,attnum from pg_attribute where attrelid='26625' order by attnum asc;
可以看到每個表上除了可見的列之外還有attrnums 1的列。這幾個列用來實現(xiàn)mvcc、表明數(shù)據(jù)的物理位置、數(shù)據(jù)所處segID...

select string_agg(attname,',' order by attnum) from pg_attribute where attrelid='26625' and attnum >0;
將所有可見列查詢出來拼接sql,屢試不爽。

2、字符串行轉列
regexp_split_to_table(string, pattern [, flags ])
regexp_split_to_table(string, pattern [, flags ])。如果沒有與pattern的匹配,該函數(shù)返回string。
如果有至少有一個匹配,對每一個匹配它都返回從上一個匹配的末尾(或者串的開頭)到這次匹配開頭之間的文本。當沒有更多匹配時,它返回從上一次匹配的末尾到串末尾之間的文本。
flags參數(shù)是一個可選的文本串,它包含零個或更多單字母標志,這些標識可以改變該函數(shù)的行為。
這個標識有很多,具體可查看http://postgres.cn/docs/9.6/functions-matching.html。不過該參數(shù)是可以省略的,我看到很少用這個flg的。

E是Posix樣式轉義字符串的前綴?,F(xiàn)代Postgres通常不需要這個,此處的E可有可無。
--\\s+ 可匹配至少一個空白字符。
--\\s 表示空白字符。包括,空格,制表符等
--\s*
--*是貪婪模式,會盡可能匹配更多的字符
--而*?是非貪婪模式 會盡量匹配少的字符
SELECT foo FROM regexp_split_to_table('the quick brown fox jumps over the lazy dog', E'\\s') AS foo;
SELECT foo FROM regexp_split_to_table('the quick brown fox', E'\\s*?') AS foo;
關于正則表達式計劃以專題來學習
幾個元字符是需要記住的:

-----------------------update 2019年10月23日11:37:32-----------------------
imagePath字符串切割處理

如果想將如上的長列轉換為多行,可通過regexp_split_to_table()來處理。處理的結果如下。

sql形如:
select regexp_split_to_table(image_path,E'\\ ') pattern from (select distinct panel_id, 'Y:\\' || prod_id || '\\' || substring( glass_id, 0, 6 )|| '\\' || substring( glass_id, 0, 9 )|| '\\' || panel_id || '\\' || 'big' || ' '||
'Y:\\' || prod_id || '\\' || substring( glass_id, 0, 6 )|| '\\' || substring( glass_id, 0, 9 )|| '\\' || panel_id || '\\' || 'small'|| ' '||
'Y:\\' || prod_id || '\\' || substring( glass_id, 0, 6 )|| '\\' || substring( glass_id, 0, 9 )|| '\\' || panel_id || '\\' || 'IMAGE' as image_path
from tabelName
where 1 = 1
and time>= '2019-09-09 00:00:00'
and time= '2019-09-10 08:00:00'
)A
3、字符串分割符
split_part(str,',',1)
select split_part('A3332-22222222','-',1); - > A3332
select split_part('A3332-22222222','-',2); - > 22222222
這個比較簡單一看便知道了。
您可能感興趣的文章:- Postgresql 截取字符串的案例
- postgresql 實現(xiàn)字符串分割字段轉列表查詢
- postgresql 查詢集合結果用逗號分隔返回字符串處理的操作
- postgresql 查詢字符串中是否包含某字符的操作
- PostgreSQL 使用raise函數(shù)打印字符串
- PostgreSQL 字符串處理與日期處理操作