简体   繁体   English

数组按字符串的一部分分组并按 postgresql 中的另一个排序

[英]array group by part of string and sort by another in postgresql

I am trying to sort the following array我正在尝试对以下数组进行排序

'{  job.8.10.2.54, job.8.11*, job.44.89.16.188, job.29292.9, job.8.1, job.8.3, job.8.2}'

as作为

'{job.29292.9, job.44.89.16.188, job.8.9.2.54, job.8.11*, job.8.3, job.8.2, job.8.1}'

So, the idea would be to group those by their body , aka "the part up to the last dot."因此,我们的想法是将它们按主体分组,也就是“到最后一个点的部分”。

Then order by the last_nb , meaning the part after the last dot ( and ignoring the * )然后按last_nb 排序,表示最后一个点之后的部分(并忽略 * )

create or replace function order_array(tasks varchar[])
returns varchar[]

language plpgsql
as $$
declare
new_array varchar[];
task varchar:='';
body varchar='';
last_nb integer;
begin

--store body
task:=tasks[1];

body:= substring(task,'.*(?=\.)\.') ;
last_nb:= substring(task, '([\d]+)\*?$');


raise notice 'body %', body;
raise notice 'last_nb %', last_nb;

new_array:=array_agg(x ORDER  BY substring(x, '([\d]+)\*?$')::INTEGER desc) FROM unnest(tasks) x;

return new_array;

end
$$;

select * from order_array('{job.8.10.2.54, job.8.11*, job.44.89.16.188, job.29292.9, job.8.1, job.8.3, job.8.2}');

Here, I am getting在这里,我得到

{job.44.89.16.188,job.8.10.2.54,job.8.11*,job.29292.9,job.8.3,job.8.2,job.8.1}

The sorting seems to be working fine, I also found a way to group with排序似乎工作正常,我也找到了一种分组方式

select array(select unnest(tasks) order by 1) as sorted_arr, count(*) from unnest(tasks) group by sorted_arr into new_array;

How could I combine those too in a single statement?我怎样才能将它们也组合在一个语句中?

Thanks!谢谢!

Finally, the solution was not to group, but order by body, then by last_nb最后解决办法不是分组,而是按body排序,然后按last_nb

CREATE OR REPLACE FUNCTION sortage(
    tasks VARCHAR[]
)
RETURNS VARCHAR[]
    LANGUAGE plpgsql
AS $$
DECLARE
    regex_body VARCHAR :='.*(?=\.)\.'; -- takes everything up to the last dot
    regex_last_nb VARCHAR :='([\d]+)\*?$'; -- takes everything after the last dot, excluding the *

BEGIN

return  array(SELECT id FROM unnest( tasks ) as id order BY substring(id,regex_body), substring(id, regex_last_nb)::INTEGER desc );


END
$$;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM