Question: How to get top dept_id of every row.
Input data
+---------+------------+----------+
| Dept_ID | PR_Dept_ID | DeptName |
+---------+------------+----------+
| 0000 | null | HR00 |
| 0001 | 0000 | HR01 |
| 0002 | 0000 | HR02 |
| 0003 | 0002 | HR03 |
| 0004 | 0002 | HR04 |
| 0005 | 0004 | HR05 |
| 0006 | null | INV00 |
| 0007 | 0006 | INV01 |
| 0008 | 0007 | INV02 |
+---------+------------+----------+
Tree level
HR00
HR01
HR02
HR03
HR04
HR05
INV00
INV01
INV02
Expected result:
+---------+------------+----------+-------------+
| Dept_ID | PR_Dept_ID | DeptName | top_Dept_ID |
+---------+------------+----------+-------------+
| 0000 | null | HR00 | null |
| 0001 | 0000 | HR01 | 0000 |
| 0002 | 0000 | HR02 | 0000 |
| 0003 | 0002 | HR03 | 0000 |
| 0004 | 0002 | HR04 | 0000 |
| 0005 | 0004 | HR05 | 0000 |
| 0006 | null | INV00 | null |
| 0007 | 0006 | INV01 | 0006 |
| 0008 | 0007 | INV02 | 0006 |
+---------+------------+----------+-------------+
What I've tried & faced problem:
If row data's level is not changed then I can use join * level count
to solve the problem. But now it's dynamic level
, e.g. HR level is 4, INV level is 3, and I have trouble at here.
I would appreciate it if someone could give me a keyword or logic.
Online test link: SQL Server 2017 | db<>fiddle