0

我正在使用 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。

现在要在网格视图中显示数据,该视图将显示部门名称及其子部门。

我的查询:

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

输出/输出:

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

如何把上面的东西拿出来?帮助赞赏!

4

1 回答 1

1

Use a 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

If the join condition has no match then all columns from dpt2 will come back as NULL so you can test for that.

Edit: I tried to fix the columns in your query as they didn't seem correct. dpt1 is your "current" table and dpt2 is where the parent will be (if any)

于 2012-12-13T12:44:12.803 回答