Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
ryan.gillies
Starting Member
27 Posts |
Posted - 2014-03-10 : 10:58:07
|
Hi all, for lack of a better word, I need to cascade a series of records in a table that are linked and group them together. Imagine the following table (dbo.Accounts) and values:CurrentAccount OldAccount001 NULL002 001003 002004 NULL005 004006 003007 005 I'd like to be able to create a recordset that creates a chain between the OldAccounts, the CurrentAccount and its future accounts - from the above example I would want to be able to group them as follows:CurrentAccount OldAccount AccountChainID001 NULL 1002 001 1003 002 1006 003 1004 NULL 2005 004 2007 005 2 I'm struggling to get my head around the logic needed to accomplish this, but its proving tricky!Does anyone have any thoughts? Thanks! |
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2014-03-10 : 11:18:27
|
[code]; with rcte as( select CurrentAccount, OldAccount, AccountChainID = row_number() over (order by CurrentAccount) from Accounts where OldAccount is null union all select a.CurrentAccount, a.OldAccount, c.AccountChainID from Accounts a inner join rcte c on a.OldAccount = c.CurrentAccount)select *from rcteorder by AccountChainID, CurrentAccount[/code] KH[spoiler]Time is always against us[/spoiler] |
|
|
ryan.gillies
Starting Member
27 Posts |
Posted - 2014-03-10 : 14:25:04
|
Recursive CTE, perfect, thank you. |
|
|
|
|
|
|
|