Here's a method to assign the group_id's to the component_id's.
It uses a recursive CTE with arrays to find the possible combinations.
The recursion starts from the lonely group_id's.
Then the next CTE picks one of the longest combinations.
WITH RECURSIVE RCTE AS (
SELECT id, group_id, component_id
, 1 as Lvl
, array[group_id] as group_ids
, array[component_id] as component_ids
FROM YourTable
WHERE group_id IN (
SELECT group_id
FROM YourTable
GROUP BY group_id
HAVING COUNT(*) = 1
)
UNION ALL
SELECT t.id, t.group_id, t.component_id
, Lvl+1
, cte.group_ids || t.group_id
, cte.component_ids || t.component_id
FROM RCTE cte
JOIN YourTable t
ON t.group_id != ALL(group_ids)
AND t.component_id != ALL(component_ids)
)
, CTE_ARRAYS AS (
SELECT group_ids, component_ids
FROM RCTE
ORDER BY array_length(group_ids, 1) desc, Lvl desc
LIMIT 1
)
SELECT a.group_id, a.component_id
FROM CTE_ARRAYS c
CROSS JOIN LATERAL UNNEST(c.group_ids, c.component_ids) WITH ORDINALITY AS a(group_id, component_id)
ORDER BY a.group_id;
group_id |
component_id |
3 |
456 |
5 |
123 |
db<>fiddle here