I have table like this,
|id | Name |sub_of|
|1 |Level 1A| 0 |
|2 |Level 1B| 0 |
|3 |Level 1C| 0 |
|4 |Level 1D| 0 |
|5 |Level 2A| 1 |
|6 |Level 2B| 2 |
|7 |Level 2C| 3 |
|8 |Level 3C| 7 |
|9 |Level 4C| 8 |
|10 |Level 5C| 9 |
|11 |Level 3B| 6 |
I this case
- A have 2 levels
- B have 3 levels
- c have 5 levels
- d have 1 levels
Sub_of is id of the previous level. Name does not contain sub_of name(ie A does not contains all level of A).
I need Maximum level of the sub_of. Please give some ideas.
Recursive cte is your friend...
Create and populate sample table (Please save us this step in your future questions)
The cte:
The query:
Results:
You need a unique identifier for each level (A, B, C, ...)
Using a recursive cte query I've used the first id where sub_of = 0 as a unique identifier:
Then simply get MAX(level) for each group.
Check it here: http://rextester.com/KIEY97438