WITHを使用して再帰で出来そうな気がしますが、条件や編集をSQL内で組み立てるのが面倒です。
例えば以下のようなSQLで経路を辿ることはできます。
step1:親子関係の状態に正規化
step2:再帰
SQL
1with step1 as (
2select 'M' as type, male_name as key_name, '' as pkey_name, groupid1 as key_groupid from 元データ
3union all
4select 'M' as type, male_name as key_name, female_name as pkey_name, groupid1 as key_groupid from 元データ
5union all
6select 'F' as type, female_name as key_name, '' as pkey_name, groupid2 as key_groupid from 元データ
7union all
8select 'F' as type, female_name as key_name, male_name as pkey_name, groupid2 as key_groupid from 元データ
9)
10, step2 as(
11select 0 as level, step1.key_name as top_Key
12 , cast(step1.key_name as varchar(100)) as all_group
13 , cast(case when type='M' then step1.key_name else '' end as varchar(100)) as mail_group
14 , cast(case when type='F' then step1.key_name else '' end as varchar(100)) as femail_group
15 , *
16from step1
17union all
18select level+ 1, step2.top_Key
19 , cast(all_group + ' > ' + step1.key_name as varchar(100))
20 , cast(mail_group + case when step1.type='M' then case when mail_group<>'' then ',' else '' end + step1.key_name else '' end as varchar(100))
21 , cast(femail_group + case when step1.type='F' then case when femail_group<>'' then ',' else '' end + step1.key_name else '' end as varchar(100))
22 , step1.*
23from step2 inner join step1 on step2.key_name=step1.pkey_name
24where step2.pkey_name<>step1.key_name
25)
26select distinct * from step2 as target
27where pkey_name<>'' and mail_group<>'' and femail_group<>''
28order by all_group
DATA
1CREATE TABLE 元データ
2 ([male_name] varchar(7), [groupid1] varchar(3), [female_name] varchar(6), [groupid2] varchar(3))
3;
4
5INSERT INTO 元データ
6 ([male_name], [groupid1], [female_name], [groupid2])
7VALUES
8 ('tarou', '001', 'hanako', '101'),
9 ('jirou', '002', 'hiroko', '102'),
10 ('jirou', '002', 'aiko', '102'),
11 ('manabu', '003', 'keiko', '102'),
12 ('manabu', '003', 'tomomi', '103'),
13 ('naoto', '004', 'tomomi', '103'),
14 ('takashi', '003', 'tomomi', '103'),
15 ('takashi', '003', 'yumi', '104')
16;
上記はまだまだ見直ししないと駄目ですけど、上記のような再帰SQLをカーソルにした、読み飛ばしや加工などを行うテーブル型を返却するストアドとするのが良さそうな気がします。