【发布时间】:2021-01-08 23:56:50
【问题描述】:
有什么办法可以按升序或降序重新排列字符串的值?
即 值:u,a,c,a 到 a,a,c,u
【问题讨论】:
-
为什么要在一个字段中存储多个值?这是解决问题的秘诀
标签: string postgresql sql-order-by postgresql-9.1 greenplum
有什么办法可以按升序或降序重新排列字符串的值?
即 值:u,a,c,a 到 a,a,c,u
【问题讨论】:
标签: string postgresql sql-order-by postgresql-9.1 greenplum
你可以通过在你的字符串上做一个 unnest 来打破多行中的值,然后对其进行分组
按 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, unnest(string_to_array(str, ',')) as str
FROM test_string
order by 1,2 desc
)
select ID, string_agg(str,',') 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, 'a,z,e');
-- Getting results in ASC order
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 ;
-- Getting results in DESC order
WITH cte AS (
SELECT id, unnest(string_to_array(str, ',')) as str
FROM test_string
order by 1,2 desc
)
select ID, string_agg(str,',') final_string
from cte
group by id
order by final_string desc;
【讨论】: