问题描述
有什么办法可以按升序或降序对字符串的值重新排序吗?
即 值:u,a,c,a 到 a,u
解决方法
您可以通过在字符串上取消嵌套来打破多行中的值,然后对其进行分组来实现这一点
按 ASC 顺序获取结果
WITH cte AS (
SELECT id,unnest(string_to_array(str,',')) as str
FROM test_string
order by 1,2
)
select ID,string_agg(str,') final_string
from cte
group by id
order by final_string ;
按 DESC 顺序获取结果
WITH cte AS (
SELECT id,2 desc
)
select ID,') final_string
from cte
group by id
order by final_string desc;
您可以使用以下代码重现该场景。
drop table if exists test_string;
create table test_string (id integer,str varchar(100));
insert into test_string (id,str) values (1,'q,w,r');
insert into test_string (id,str) values (2,'a,e,c');
insert into test_string (id,str) values (3,z,e');
-- Getting results in ASC order
WITH cte AS (
SELECT id,') final_string
from cte
group by id
order by final_string ;
-- Getting results in DESC order
WITH cte AS (
SELECT id,') final_string
from cte
group by id
order by final_string desc;