SQL hiearchy选择两个表之间的查询

时间:2015-10-09 06:43:17

标签: c# sql sql-to-linq-conversion

我有2张桌子(人物,部门)。

部门表格如下:

ID (int)
Name (varchar)
ParentID (int)

人员表格如下:

Id (int)
FirstName (varchar)
SureName (varchar)
DepartmentId (int)
Manager (Bool)
Asistant (Bool)

我需要创建查询,选择具体人员的所有直接下属,即具体人员的经理。而一个查询选择所有不仅直接下属的经理。 每个部门都有一名经理和一名助理。经理==假的人是直接下属,子女的人是父母堕落的下属。

我不知道如何在SQL / LINQ中创建这些查询。

我将不胜感激任何帮助!

实施例: DEPARTMENT

Id   Name          Parent
0    Department1   null
1    Department2   0
2    Department3   1

示例:

People
ID    Name      Department    DepartmentId    Manager    Asistant
1     Martin    Joshua            0             1           0
2     Ondra     Joshua2           0             0           0
3     Petr      Joshua3           0             0           0
4     Todd      Joshua3           1             1           0
5     Alex      Joshua3           1             0           0
6     Iva       Joshua3           1             0           0
7     Otto      Joshua3           2             1           0
8     Todd      Joshua3           2             0           0

我需要exmple选择所有(不仅是直接)经理的部门,其中id为0,结果如下:

2     Ondra     Joshua2           0             0           0
3     Petr      Joshua3           0             0           0
4     Todd      Joshua3           1             1           0
5     Alex      Joshua3           1             0           0
6     Iva       Joshua3           1             0           0
7     Otto      Joshua3           2             1           0
8     Todd      Joshua3           2             0           0

我不确定直接下属的SQL查询:

SELECT * FROM dbo.PeopleView WHERE DepartmentId = 162 AND Manager = 0; -- all direct s (162)

解决方案:

;WITH CTE AS
(
    SELECT 1 as EMPLEVEL, H1.Id, H1.ParentId, H1.Name FROM DepartmentView H1 WHERE Id = 6
    UNION ALL
    SELECT EMPLEVEL + 1, H2.Id, H2.ParentId, H2.Name FROM DepartmentView H2
    INNER JOIN CTE ON H2.ParentId = CTE.Id
)
SELECT DISTINCT P.Id, P.LastName,P.FirstName,P.DepartmentId,P.Manager,P.Assistant FROM CTE as T JOIN PeopleView as P on T.Id = P.DepartmentId;

1 个答案:

答案 0 :(得分:1)

对于您的第一个查询,以及@Andrew的评论说,递归查询可以帮助解决这个问题:

;WITH CTE
AS
(
SELECT ID,FirstName,SureName,DepartmentID,Manager,Assistant, 0 AS EMPLEVEL  FROM PEOPLE A  WHERE DepartmentId = 1 AND Manager = 0
UNION ALL 
SELECT B.ID,B.FirstName,B.SureName,B.DepartmentID,B.Manager,B.Assistant,EMPLEVEL +1 FROM PEOPLE B 
INNER JOIN DEPARTMENT D
ON B.DepartmentID = D.ID
INNER JOIN CTE 
ON D.ParentID = CTE.DepartmentID 
)
SELECT DISTINCT * FROM CTE 

要转换为LINQ,你可以阅读这篇文章:P: Common Table Expression (CTE) in linq-to-sql?

希望得到这个帮助,最好的问候。