如何在ASP.NET中使用自联接获取GridView中的所有行?

时间:2012-12-13 12:38:51

标签: asp.net sql-server-2008 gridview self-join

我正在使用Self Join从SQLSERVER数据库中检索数据并在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和Logistics,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 个答案:

答案 0 :(得分: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是父级所在的位置(如果有的话)