<bdo id="vljxk"><rt id="vljxk"><noframes id="vljxk"><noframes id="vljxk"><noframes id="vljxk"><rt id="vljxk"></rt><rt id="vljxk"></rt><noframes id="vljxk"><rt id="vljxk"><delect id="vljxk"></delect></rt><noframes id="vljxk"><rt id="vljxk"></rt><noframes id="vljxk"><noframes id="vljxk"><rt id="vljxk"></rt>

當前位置:首頁 >  站長 >  數據庫 >  正文

postgresql 實現將數組變為行

 2021-05-21 16:55  來源: 腳本之家   我來投稿 撤稿糾錯

  阿里云優惠券 先領券再下單

這篇文章主要介紹了postgresql 實現將數組變為行的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧。

有的時候需要把數組元素同表中的字段進行關系運算,首先得把array變為記錄行

SELECT "unnest"(array[1,2,3])

結果:
unnest

 

求數組交集:

SELECT "unnest"(array[1,2,3]) INTERSECT SELECT "unnest"(array[3,4,5])

結果:
unnest
3

補充:PostgreSQL單列多行變一行&一行變多行

工作中經常遇到這樣一個場景,希望將某個字斷查詢出得結果組合成為一個字符串,用逗號分割(或者分號),通過PG中的函數該如何實現?

多行變一行

實例表:

想要的結果:

方法一:string_agg(字段名,分隔符)

select id,string_agg(name,',') AS NAME_NEW from test
group by 1
ORDER BY 1

 

方法二:array_agg(字段名)

select id,array_agg(name)
AS NAME_NEW from test
group by 1
ORDER BY 1;

select id,array_to_string(array_agg(name),',')
AS NAME_NEW from test
group by 1
ORDER BY 1;
另外:array_agg(distinct(字段名)) 拼接唯一的字段。

一行變多行

select id,regexp_split_to_table(name_new,',')
AS NAME from test;

select id,unnest(string_to_array(name_new,','))
AS NAME from test;

文章來源:腳本之家

來源地址:https://www.jb51.net/article/204927.htm

申請創業報道,分享創業好點子。點擊此處,共同探討創業新機遇!

相關文章

熱門排行

信息推薦