我们需要通过SQL将“活动”帐户记录的层次结构返回为特定格式。
以下是我的示例数据和预期结果的链接:SAMPLEDATA
注意事项:
我已经掌握了帐户的整个层次结构(递归CTE)。但是,问题出在父帐户和“根”列。如果层次结构复杂或父母不活跃,我似乎无法为其获取正确的值。 (例如,如果最上层的父级处于非活动状态,或者有多个父级帐户而某些处于非活动状态)
我尝试为这些列使用子查询,但是我认为我仍然缺少某些东西...
有人可以用正确的方法启发我吗?预先感谢!
这是我的剧本:
WITH aCTE ([Client Number], [Client Level], accountid) AS
(
SELECT
ROW_NUMBER() OVER (ORDER BY parentaccountid ASC) [Client Number]
,0 [Client Level]
,accountid
FROM
Account
WHERE
parentaccountid IS NULL
UNION ALL
SELECT
b.[Client Number]
,b.[Client Level] + 1
,a.accountid
FROM
Account a
JOIN aCTE b ON a.parentaccountid = b.accountid
WHERE
a.statecode = 0 --Active
)
SELECT DISTINCT
ac.[Client Number]
,ac.[Client Level]
,fa.accountnumber [Account Number]
,fa.[name] [Account Name]
,[Parent Account] = CASE
WHEN (SELECT TOP 1 a.[name] FROM Account a JOIN aCTE b ON a.accountid = b.accountid
WHERE b.[Client Number] = ac.[Client Number]
ORDER BY b.[Client Level] ASC) != fa.[name]
THEN fa.parentaccountidname
ELSE ''
END
,[Root Parent Number] = (SELECT TOP 1 a.accountnumber FROM Account a JOIN aCTE b ON a.accountid = b.accountid
WHERE b.[Client Number] = ac.[Client Number]
ORDER BY b.[Client Level] ASC)
,[Root Parent Name] = (SELECT TOP 1 a.[name] FROM Account a JOIN aCTE b ON a.accountid = b.accountid
WHERE b.[Client Number] = ac.[Client Number]
ORDER BY b.[Client Level] ASC)
FROM
FilteredAccount fa
JOIN aCTE ac ON fa.accountid = ac.accountid
WHERE
fa.statecode = 0 --Active
ORDER BY
ac.[Client Number] ASC
,ac.[Client Level] ASC