I have hierarchical data stored in my table [AdjT] in SQL Server 2014. The total depth of data is 4 levels and is fixed.
i.e., [Parent - Child1 - Child2 - Child3]
The columns are: Adjt {Id, ParentId, Title, TypeM}
You can see the data in the image.

Multiple hierarchies (as per TypeM) are present in same table (you can see 2 parents)
What I require?
I need to fetch all the parent "Title" for any given Child.
e.g., below image shows the "hierarchy" for Id:4 for TypeM:AAA

What I have done so far
This query gives me the child row and its immediate parent.
select a.Title as P1, (select a1.Title from AdjT as a1 where a1.Id=a.ParentId) as P1 from Adjt as a where a.TypeM='AAA' and a.Id=4;
like this:
The issue:
But when I try to access P3 based on P2's ParentId, I get an error.
[The multi-part identifier "a1.ParentId" could not be bound.]
as per the below query:
select
a.Title as P1
, (select a1.Title from AdjT as a1 where a1.Id=a.ParentId) as P2
, (select a2.Title from AdjT as a2 where a2.Id=a1.ParentId) as P3 --"a1.ParentId" ERROR
from
Adjt as a
where a.TypeM='AAA'
and a.Id=4;
Even if I write as P2.ParentId, it gives me:
The multi-part identifier "P2.ParentId" could not be bound.
What can I do to get this to work?
The workaround that I am using currently
I am using nested query to get to the data and hierarchy that I require.
Its done using the below query:
select
a.Title as P1
, (select a1.Title from AdjT as a1 where a1.Id=a.ParentId) as P2
, (select a2.Title from AdjT as a2 where a2.Id=(select a1.ParentId from AdjT as a1 where a1.Id=a.ParentId)) as P3
, (select a3.Title from AdjT as a3 where a3.Id=(select a2.ParentId from AdjT as a2 where a2.Id=(select a1.ParentId from AdjT as a1 where a1.Id=a.ParentId))) as P4
from
Adjt as a
where a.TypeM='AAA'
and a.Id=4;
Is there any better way to do this? Why can I only access the first column's parentId?
I cannot edit the schema of the table or how data is stored. The hierarchy must be fetched from bottom-up using leaf node's Id as shown above.
I tried to use CTE to get hierarchical data, but I want it as "columns" not "rows". Converting those CTE rows to columns in "code" is also not an option.
If any one can suggest a better way to do this, it would be most helpful.
Thank you for reading my question, any help would be appreciated.
JOINs work. They are an invaluable part of SQL. The many subqueries that you use will result in very sloppy and hard to read (and maintain) code that will likely perform very badly. If you are going to be doing more SQL programming in the future, you should read some introductory books on the topic.