任务:
表EmployeesInfo包含列:EmplId,EmplName,EmplCar,ChiefId 任务:选择只有首席分配的员工,分配的负责人必须有车,并且应该至少有三个直接下属(Chief的直接下属是在他的ChiefID专栏中具有主要权限的员工)。
输出列:EmplId,EmplName,ChiefId,ChiefCar,下属次数
注意: Chief也是ChiefId = NULL的员工。
问题: 这项任务的最佳解决方案是什么?我有一个,但我觉得它太可怕了。
添加:我正在使用SQL Server。如果您将使用它来解决此任务将是非常好的。谢谢。
我的解决方案:
SELECT E.EmpId, E.EmpName, E.ChiefId, B.EmpCar AS [Chief Car]
,
(SELECT COUNT(EE.EmpId) FROM EmployeeInfo AS EE
INNER JOIN EmployeeInfo BB ON EE.ChiefId = BB.EmpId WHERE EE.ChiefId = E.ChiefId AND E.ChiefId IN
(
SELECT BB.EmpId
FROM EmployeeInfo AS BB
INNER JOIN EmployeeInfo AS EE
ON BB.EmpId = EE.ChiefId
GROUP BY BB.EmpId
HAVING COUNT(EE.EmpId) >= 3
)
)
AS [Subordinate Count]
FROM EmployeeInfo AS B
LEFT JOIN EmployeeInfo AS E
ON E.ChiefId = B.EmpId
WHERE B.EmpCar IS NOT NULL AND E.ChiefId IN
(
SELECT B2.EmpId
FROM EmployeeInfo AS B2
INNER JOIN EmployeeInfo AS E2
ON B2.EmpId = E2.ChiefId
GROUP BY B2.EmpId
HAVING COUNT(E2.EmpId) >= 3
);
部分数据:
其次是EmpId,EmpName,EmpCar,ChiefId
1,Emp1,NULL,4
2,Emp2,NULL,4
3,Emp3,NULL,4
4,Chief1,Somecar1,NULL
5,Emp4,NULL,7
6,Emp5,NULL,7
7,Chief2,Somecar2,NULL
期望的结果:
其次是EmpId,EmpName,ChiefId,ChiefCar,下属计数
1,Emp1,4,Somecar1,3
2,Emp2,4,Somecar1,3
3,Emp3,4,Somecar1,3
答案 0 :(得分:0)
下面的解决方案可以帮助您,它在SQL中: -
SELECT distinct x.Employeeinfo from EmployeeInfo x, EmployeeInfo y
where y.CheflID IN (Select y.CheflID from EmployeeInfo y)
and x.CheflId=y.CheflID;
希望你能得到你正在寻找的东西......
答案 1 :(得分:0)
可能的解决方案:
SELECT E.EmpId, E.EmpName, B.EmpId AS [Chief Id], B.EmpCar AS [Chief Car],
(SELECT COUNT(EmpId) FROM Employees WHERE ChiefId = B.EmpId) AS [Subordinate Count]
FROM Employees AS E
INNER JOIN Employees AS B
ON E.ChiefId = B.EmpId
WHERE 3 <= (SELECT COUNT(EmpId) FROM Employees WHERE ChiefId = B.EmpId)
AND B.EmpCar IS NOT NULL