Skip to content
Advertisement

Recursively Conditionally get parent Id

I have two tables: Budget Line and Expense. They are structured in such a way that an expense must have either a parent record in the budget line table, or a parent record in the expense table. I need to select all child-most expenses for each budget line.

For example – BudgetLine:

Id Description
1 TEST123
2 OTHERTEST

Expense:

Id ParentId ParentType Description
1 1 BudgetLine Group of Expenses
2 1 Expense Expense # 1
3 1 Expense Expense # 2
4 2 BudgetLine Expense 3

Desired result:

BudgetLineId ExpenseId Description
1 2 Expense # 1
1 3 Expense # 2
2 4 Expense # 3

I am looking to omit expenses in the result only if they are the only sub-child. Note that an expense may have many children, grandchildren, etc.

I have tried the following, and researching various recursive CTE methods:

Which did in-fact obtain all the child Expenses and their associated parent BudgetLine, but it also included the middle-tier expenses (such as item 1 in the example) and I cannot figure out how to filter those middle-tier items out.

Here is a script to create tables / insert sample data:

Advertisement

Answer

Maybe I have oversimplified, but the following returns your desired results, by checking that there is no other expense row connected to the current row.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement