declare @Codes table(ID int, CodeValue varchar(10), CodeGroup varchar(10), CodeDesc varchar(20))
declare @Mapping table(ID int, CodeID int, ParentCodeID int)
insert into @Codes values
(1, 'Person 1', 'Accounts', 'cashier'),
(2, 'Person 2', 'Finance', 'teller'),
(3, 'Person 3', 'HR', 'administrator'),
(4, 'Person 4', 'IT', 'system admin'),
(5, 'Person 5', 'Accounts', 'accountant'),
(6, 'Person 6', 'Finance', 'Investbanker')
insert into @Mapping values
(1, 1, null),
(2, 2, 1),
(3, 3, 1),
(4, 4, null),
(5, 3, 4),
(6, 5, null),
(7, 6, 1)
select
CRoot.CodeGroup as '@group',
(select
CChild.CodeGroup as '@group',
CChild.CodeValue as 'CodeParent/@name',
CChild.CodeDesc as 'CodeParent/@desc'
from @Mapping as MChild
inner join @Codes as CChild
on MChild.CodeID = CChild.ID
where MChild.ParentCodeID = MRoot.ID
for xml path('ChildCodes'), type)
from @Mapping as MRoot
inner join @Codes as CRoot
on MRoot.CodeID = CRoot.ID
where
MRoot.ParentCodeID is null
for xml path('CodeParent'), root('Codes')
Результат
<Codes>
<CodeParent group="Accounts">
<ChildCodes group="Finance">
<CodeParent name="Person 2" desc="teller" />
</ChildCodes>
<ChildCodes group="HR">
<CodeParent name="Person 3" desc="administrator" />
</ChildCodes>
<ChildCodes group="Finance">
<CodeParent name="Person 6" desc="Investbanker" />
</ChildCodes>
</CodeParent>
<CodeParent group="IT">
<ChildCodes group="HR">
<CodeParent name="Person 3" desc="administrator" />
</ChildCodes>
</CodeParent>
<CodeParent group="Accounts" />
</Codes>