0
我正在使用Self Join從SQLSERVER數據庫檢索數據並在GridView中顯示數據。如何在ASP.NET中使用Self Join獲取GridView中的所有行?
數據在DepartmentMst表:
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
從以上數據可以看出,AdminPanel部門都有SUBDEPARTMENT TestDepartment和物流既DepartmentParentID = 3屬於主要部門即AdminPanel。
現在想要在網格視圖中顯示數據,它將顯示DepartmentName及其子部分。
我的查詢:
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
但是,我需要所有SubDepartmentName的DepartmentName的。如果任何部門沒有父即DepartmentParentID = 0,那麼它必須顯示爲MainDepartment否則其上級部門名稱
如:
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
如何得到上面放出來? 幫助讚賞!
感謝回答@CyberDude但在他們的數據庫中列DepartmentParentID他們是零(0)確定爲MainDept –
是沒有NULL值,並且由於沒有部門有'Id = 0',那麼連接條件將不會產生匹配。在這種情況下,使用'dpt2'別名輸出的任何列都將以NULL結尾。爲了更好地理解剛纔運行這個查詢會發生什麼:'SELECT dpt1。*,dpt2。* FROM DepartmentMst dpt1 LEFT JOIN DepartmentMst dpt2 ON dpt2.DepartmentID = dpt1.DepartmentParentID' – CyberDude
表是一樣的,只是我已經使用self!如果我沒有錯你的查詢顯示錯誤「轉換失敗時,將varchar值'MainDept'轉換爲數據類型int」 –