2012-12-13 41 views
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 

如何得到上面放出來? 幫助讚賞!

回答

1

使用LEFT JOIN:

SELECT 
    dpt1.DepartmentID as DepartmentID 
    ,dpt1.DepartmentName as DepartmentName 
    ,dpt2.DepartmentParentID as ParentDepartmentID 
    ,ISNULL(dpt2.DepartmentName, 'MainDept') as ParentDepartment 
    ,dpt1.IsActive 
FROM DepartmentMst dpt1 
    LEFT JOIN DepartmentMst dpt2 
     ON (dpt2.DepartmentID = dpt1.DepartmentParentID) and dpt2.IsActive=1 
ORDER BY DepartmentID 

如果連接條件沒有匹配,那麼從dpt2所有列會回來爲NULL,所以你可以測試這一點。

編輯:我試圖修復您的查詢中的列,因爲他們似乎不正確。 dpt1是你的「當前」表和dpt2就是家長會(如果有的話)

+0

感謝回答@Cyber​​Dude但在他們的數據庫中列DepartmentParentID他們是零(0)確定爲MainDept –

+0

是沒有NULL值,並且由於沒有部門有'Id = 0',那麼連接條件將不會產生匹配。在這種情況下,使用'dpt2'別名輸出的任何列都將以NULL結尾。爲了更好地理解剛纔運行這個查詢會發生什麼:'SELECT dpt1。*,dpt2。* FROM DepartmentMst dpt1 LEFT JOIN DepartmentMst dpt2 ON dpt2.DepartmentID = dpt1.DepartmentParentID' – CyberDude

+0

表是一樣的,只是我已經使用self!如果我沒有錯你的查詢顯示錯誤「轉換失敗時,將varchar值'MainDept'轉換爲數據類型int」 –

相關問題