-2

Put a series numbers together, in multiple columns, here is the series. We need to solve the problem Postgres. Each row has comma separated values.

Here's the problem. When I have groups of concated values, that are comma seperated. I need to group them by related numbers in those groups.

For instance. if we have 1,3, it would group together with 1,2,3,4.

1,18 would group together with 1,2,3,4,18. Because the group has a 1 in it. The 2 at the top of the list, would reduce down to 1,2,3,4.

Basically all I"m looking to do, is group the rows of comma seperated numbers together, if match 1 of any other group of numbers. So merge the numbers, if any of the other numbers are matching.

IDS
-------------
2 
1,3
1,2,3,4
1,18
1,4
5,6
5,6,7,8
5,7
1,3
10,11,12
10,13
13,14
10
6,22

When you group them,

The query would then returns the values as such. Here is a merged list of numbers based on the numbers above. Output =

IDS
-------------
1,2,3,4,18
5,6,7,8,22
10,11,12,13,14

a simple example.

If you have a list

1,2 1,3 4,5 5,6

The query would return

1,2,3
and 4,5,6

because 1 and 1 are alike and 5 and five are a like, so they merge.

2
  • `"when you group them" - group by what? Aug 16 at 11:12
  • @a_horse_with_no_name Looks like undirected graph grouping Aug 16 at 13:53
0

I'm not sure I understood your problem, but if you are looking to remove duplicates from your strings, you could try something like:

select array_to_string(array_agg(x), ',') as res from (
    select distinct row_number() over () as n
         , unnest(string_to_array(ids, ',')) as x 
    from t
) as tt
group by n;

Fiddle

1
  • What I'm looking to do is merge sets of like numbers. Such as 1,2 is one set, 1,4,6. that would merge to 1,2,4,6 another set would be 13,15,33,55 and 13,88,23 This would merge to 13,15,23,33,55,88. The reason being is that they have a single number in common. So if one rows comma seperated number has any single number in common with another, then they concat into one row. Aug 16 at 14:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.