I have data in following format
Table1
e_id e_name e_type
-------------------------
1 CBC 2
2 ABC 3
3 N2 1
4 CBC1 3
5 ABC1 3
6 N1 1
table2
N_ID N_Name
---------------
3 N2
6 N1
Table3
N_ID E_ID
------------
3 1
3 2
3 3
6 4
6 5
6 6
And i want to build a hierarchy as follows
e_id e_name e_type n_id
------------------------------------
6 N1 1 6
4 - ABC1 3 6
5 - CBC1 3 6
3 N2 1 3
4 - ABC 3 3
5 - CBC 2 3
with Order by Nodes (Asc), child nodes (Asc)
I tried doing something similar to this
SELECT u.e_id,
CASE WHEN e_TYPE_ID = 1 THEN u.e_name ELSE ' - ' + u.e_name END e_name,
e_TYPE_ID, su.n_ID
FROM table1 u
INNER JOIN table3 su on u.e_id = su.e_id
WHERE EXISTS (SELECT N_ID FROM table2 WHERE N_ID = CASE WHEN u.e_TYPE_ID = 1 THEN u.e_id ELSE n_ID END)
ORDER BY e_TYPE_ID, u.e_name,n_id
But not able to get correct order, is there a better way to do this?