Доброе утро,
Если так, то попробуйте следующий скрипт:
X++:
Create Table #tmp(id int identity(1,1), AccountId Uniqueidentifier, IsParent bit)
Insert Into #tmp(AccountId, IsParent)
Select
a1.AccountId
,1
From FilteredAccount a1
Where a1.parentaccountid Is Null and Exists (Select * From FilteredAccount a where a.parentaccountid = a1.accountid)
Select
(case t1.IsParent When 1 Then fa1.Name else null end) ParentAccountName
,(case t1.IsParent When 0 Then fa1.Name else null end) ChildAccountName
,fa1.address1_city
,fa1.address1_stateorprovince
From
(Select AccountId, id, IsParent From #tmp
Union All
Select
fa.AccountId, t.id, 0 as IsParent
From FilteredAccount fa
Inner Join #tmp t on fa.parentaccountid = t.AccountId) t1
Inner Join FilteredAccount fa1 on t1.AccountId = fa1.accountid
Order By t1.id asc, t1.IsParent desc
drop Table #tmp