SQL remove duplicates from comma separated string:
Псевдокод: Направете функция postgresql, която получава като вход низа, разделен със запетая, и създава друг масив в паметта. Разделете низа на запетая, изрежете интервала и избройте всеки елемент, ако елементът не се показва в новия списък, след това го добавете. Накрая изравнете новия масив до низ и връщане.
drop function if exists remove_duplicates_from_comma_separated_string(text);
CREATE or replace FUNCTION remove_duplicates_from_comma_separated_string(arg1 text)
RETURNS text language plpgsql AS $$ declare
item text;
split_items text[];
ret_items text[];
ret_val text;
BEGIN
--split your string on commas and trim whitespace
split_items := string_to_array(ltrim(arg1), ',');
--enumerate each item, if it doesn't exist in the new array then add it.
FOREACH item IN ARRAY split_items LOOP
if ( item::text = ANY(ret_items)) then
else
--append this unique item into ret_items
select array_append(ret_items, ltrim(item)) into ret_items;
end if;
END LOOP;
--flatten the final array to a text with comma delimiter
SELECT array_to_string(ret_items, ',', '*') into ret_val;
return ret_val;
END; $$;
Така че сега можем да извикаме функцията на таблица по този начин:
drop table if exists foo_table;
create table foo_table(name text);
insert into foo_table values('karim,karim,rahim,masud,raju,raju');
insert into foo_table values('jon,man,jon,kamal,kamal');
insert into foo_table values('jon,man,kamal');
insert into foo_table values('c,abc,poty');
insert into foo_table values('c,abc,abc,kotb');
select remove_duplicates_from_comma_separated_string(name) from foo_table;
Кое отпечатва:
┌───────────────────────────────────────────────┐
│ remove_duplicates_from_comma_separated_string │
├───────────────────────────────────────────────┤
│ karim,rahim,masud,raju │
│ jon,man,kamal │
│ jon,man,kamal │
│ c,abc,poty │
│ c,abc,kotb │
└───────────────────────────────────────────────┘
Фактор haaax на миризмата на кода: 9,5 от 10. Строителният екип гледа как начинаещият програмист удря пирон с тръбния ключ за 90 долара, всички въртят очи.
person
Eric Leschinski
schedule
25.07.2021