我在postgresql中有一个表,其文本列的值如下:
column
-----------
CA;TB;BA;CB
XA;VA
GA;BA;LA
我想对每个值中的元素进行排序,以便查询结果如下:
column
-----------
BA;CA;CB;TB
VA;XA
BA;GA;LA
我已尝试使用 string_to_array , regexp_split_to_array , array_agg ,但我似乎无法接近它。
感谢。
答案 0 :(得分:0)
我可能过度复杂了:
t=# with a(c)as (values('CA;TB;BA;CB')
,('XA;VA')
,('GA;BA;LA'))
, w as (select string_agg(v,';') over (partition by c order by v), row_number() over (partition by c),count(1) over(partition by c) from a,unnest(string_to_array(a.c,';')) v)
select * from w where row_number = count;
string_agg | row_number | count
-------------+------------+-------
BA;CA;CB;TB | 4 | 4
BA;GA;LA | 3 | 3
VA;XA | 2 | 2
(3 rows)
这里有一个丑陋的黑客:
with a(c)as (values
('CA;TB;BA;CB')
,('XA;VA')
,('GA;BA;LA'))
select translate(array_agg(v order by v)::text,',{}',';') from a, unnest(string_to_array(a.c,';')) v group by c;
translate
-------------
BA;CA;CB;TB
BA;GA;LA
VA;XA
(3 rows)
答案 1 :(得分:0)
我希望这很容易理解:
WITH tab AS (
SELECT
*
FROM
unnest(ARRAY[
'CA;TB;BA;CB',
'XA;VA',
'GA;BA;LA']) AS txt
)
SELECT
string_agg(val, ';')
FROM (
SELECT
txt,
regexp_split_to_table(txt, ';') AS val
FROM
tab
ORDER BY
val
) AS sub
GROUP BY
txt;
首先,我将值拆分为行(regexp_split_to_table
)并进行排序。然后group by
原始值并再次加入string_agg
。
输出:
BA;CA;CB;TB
BA;GA;LA
VA;XA