This
article[
^] from Pinal Dave explains how to use Recursive CTEs to produce the Hierarchical results that you are after.
I came back to this to give a fuller explanation in light of your specific question as it can also be achieved using nested CTEs.
I decided that my anchor statement was
select distinct medium as detail, 2 as detlev, medium, class from #student
as I can easily get the class names and I know they will be level 1.
To get my recursion I added
UNION ALL
SELECT S.sname as detail, M1.detlev + 1, s.medium, S.class FROM #student S
INNER JOIN CTE1 M1 ON S.class = M1.Class and S.Medium = M1.detail
which gave me results of
English 2 English class-1
french 2 french class-3
Hindi 2 Hindi class-1
Hindi 2 Hindi class-2
russian 2 russian class-3
std11 3 russian class-3
std12 3 russian class-3
std6 3 Hindi class-2
std7 3 Hindi class-2
std1 3 Hindi class-1
std2 3 Hindi class-1
std3 3 Hindi class-1
std8 3 french class-3
std9 3 french class-3
std10 3 french class-3
std4 3 English class-1
std5 3 English class-1
I then needed to UNION those results with the class names
select distinct class as detail, class, CAST(NULL as varchar(20)) as medium, 1 as detlev from #student
so my entire query became
;WITH CTE1 AS
(
select distinct medium as detail, 2 as detlev, medium, class from #student
UNION ALL
SELECT S.sname as detail, M1.detlev + 1, s.medium, S.class FROM #student S
INNER JOIN CTE1 M1 ON S.class = M1.Class and S.Medium = M1.detail
),
CTE2 AS
(
SELECT DISTINCT detail, class, medium, detlev FROM CTE1 c1
UNION ALL
select distinct class as detail, class, CAST(NULL as varchar(20)) as medium, 1 as detlev from #student
)
SELECT detail FROM CTE2
order by class, medium, detlev,detail
giving me my final results of
class-1
English
std4
std5
Hindi
std1
std2
std3
class-2
Hindi
std6
std7
class-3
french
std10
std8
std9
russian
std11
std12
Note these results are different to those in your original question - that threw me for a moment until I determined that the expected results you quoted are not quite right given the data supplied.