I am using Self Join to retrieve data from SQLSERVER Database and displaying the data in GridView.
Data in DepartmentMst table:
DepartmentID DepartmentName IsActive DepartmentParentID
3 Admin Panel 1 0
4 Human Resource 1 0
5 Information Technology 1 0
6 Operational 1 0
21 TestDepartment 1 3
22 Logistics 1 3
From above data you can see that AdminPanel Department has its SubDepartment TestDepartment and Logistics with both DepartmentParentID=3 which belongs to main Department i.e AdminPanel.
Now want to display the Data in grid view which will show the DepartmentName and its SubDepartments.
My Query:
SELECT dpt1.DepartmentID as DepartmentID
,dpt1.DepartmentName as DepartmentName
,dpt1.DepartmentParentID as ParentDepartmentID
,dpt2.DepartmentName as ChildDepartment
,dpt1.IsActive
FROM DepartmentMst dpt1,DepartmentMst dpt2
where (dpt1.DepartmentID=dpt2.DepartmentParentID) and dpt2.IsActive=1
order by DepartmentID
O/P:
DepartmentID DepartmentName ParentDepartmentID ChildDepartment IsActive
3 Admin Panel 0 TestDepartment 1
3 Admin Panel 0 Logistics 1
But, I need all the DepartmentName with SubDepartmentName. If any Department has no Parent i.e DepartmentParentID=0, then it must be Shown as MainDepartment else its Parent Department Name
Eg:
DepartmentID DepartmentName IsActive DepartmentParentID ParentDeptName
3 Admin Panel 1 0 MainDept
4 Human Resource 1 0 MainDept
5 Information Technology 1 0 MainDept
6 Operational 1 0 MainDept
21 TestDepartment 1 3 AdminPanel
22 Logistics 1 3 AdminPanel
How to get the above out put?
Help Appreciated!
Use a LEFT JOIN:
If the join condition has no match then all columns from
dpt2will come back asNULLso you can test for that.Edit: I tried to fix the columns in your query as they didn’t seem correct.
dpt1is your “current” table anddpt2is where the parent will be (if any)