我有下表:
Account_Number Parent_Account Child_Account
R003247 R000355 R000002
R000355 NULL R003247
R000002 R003247 NULL
R004853 NULL R028636
R004853 NULL R028638
R004853 NULL R028637
R028636 R004853 NULL
R028638 R004853 NULL
R028637 R004853 NULL
可以加载:
create table dbo.temptable
(Account_Number varchar(10),
Parent_Account varchar(10),
Child_Account varchar(10))
insert into dbo.temptable
values
('R003247','R000355','R000002'),
('R000355',NULL,'R003247'),
('R000002','R003247',NULL),
('R004853',NULL,'R028636'),
('R004853',NULL,'R028638'),
('R004853',NULL,'R028637'),
('R028636','R004853',NULL),
('R028638','R004853',NULL),
('R028637','R004853',NULL)
此表表示帐号的拆分和重新分配。 它与跟踪地块的分割和组合有关。
如上表所示,前三行应组合在一起,因为它从R000355
-->R003247
-->R000002
最后 6 个,如上表所示,也应该分组,因为它显示R004853
被分成三个R028636
,R028637
、R028638
。
我已经尝试了许多类似的东西的变化:
SELECT CE.*,TT.ID
FROM dbo.temptable CE
INNER JOIN
(
SELECT ACCOUNT_NUMBER,ROW_NUMBER() OVER (ORDER BY ACCOUNT_NUMBER) AS ID
FROM(
SELECT DISTINCT ACCOUNT_NUMBER FROM dbo.temptable where Child_Account is not null)AA
)TT
ON TT.ACCOUNT_NUMBER = CE.Account_Number OR TT.Account_Number = CE.Child_Account
哪个大喊:
Account_Number Parent_Account Child_Account ID
R000355 NULL R003247 1
R003247 R000355 R000002 2
R000355 NULL R003247 2
R004853 NULL R028636 3
R004853 NULL R028638 3
R004853 NULL R028637 3
当我真正需要的是:
Account_Number Parent_Account Child_Account ID
R000355 NULL R003247 1
R003247 R000355 R000002 1
R000002 R003247 NULL 1
R004853 NULL R028636 2
R004853 NULL R028638 2
R004853 NULL R028637 2
R028636 R004853 NULL 2
R028638 R004853 NULL 2
R028637 R004853 NULL 2
这个问题没什么可怕的,一旦你跳进去,给自己一个腕管,因为在手机上打字太多。 这只是一个稍微修改的标准递归分层查询问题。 值得注意的是,递归中的连接条件是当前帐号是某个父帐户的子帐户。 至于编号,我们只使用DENSE_RANK
而不是顶级父母。
WITH cte AS (
SELECT m.*, DENSE_RANK() OVER (ORDER BY m.Account_Number) AS pos
FROM temptable m
WHERE Parent_Account IS NULL
UNION ALL
SELECT m.*, cte.pos
FROM temptable m
INNER JOIN cte
ON m.Account_Number = cte.Child_Account
)
SELECT *
FROM cte
ORDER BY pos;
演示
注意:我在这里对@Quassnoi写的精彩的公认答案给予了极大的赞扬。