CREATE TABLE employee(
empId INTEGER,
empName VARCHAR(20),
mgrId INTEGER,
salary DECIMAL(12,2)
);
INSERT INTO employee VALUES
(1, 'A', 2, 100),
(2, 'B', 4, 150),
(3, 'C', 4, 165),
(4, 'D', 7, 200),
(5, 'E', 6, 210),
(6, 'F', 7, 250),
(7, 'G', 7, 300),
(8, 'H', 6, 170);
链接到SQL小提琴:http://sqlfiddle.com/#!9/cd4be8
此示例数据产生此层次结构。
每个员工都有一个直接上司。而且,所有比某个雇员年长的雇员都被称为他们的间接上司。
在给定的样本中,A的直接凸台是B,C、D、E、F、G和H是A的间接凸台。我必须找到两样东西。
对于每个员工,找到比该员工高级的所有员工的计数(直接上司+间接上司的数量)。
预期产量:
+---------+-------+
| empName | total |
+---------+-------+
| A | 7 |
| B | 3 |
| C | 3 |
| D | 1 |
| E | 3 |
| F | 1 |
| G | 0 |
| H | 3 |
+---------+-------+
对于每个员工,找到间接上司的方式应确保间接上司的工资至少是给定员工工资的两倍,但在间接上司中是最低的。
预期产量:
+---------+------+
| empName | mgr |
+---------+------+
| A | D |
| B | G |
| C | NULL |
| D | NULL |
| E | NULL |
| F | NULL |
| G | NULL |
| H | NULL |
+---------+------+
说明:对于员工A(工资=100),至少双倍工资的间接上司为D(工资=200)、F(工资=210)和G(工资=300)。但由于D的工资是D,F和G的最低工资,所以结果是D。
很容易找到员工下属的人数,但另一方面却很棘手。如有任何帮助/提示,将不胜感激。
最佳答案
我希望你能找到以下的答案,直到找到一个更好的解决方案。
第一步创建一个记录员工级别的新视图。在这种情况下,名为G的“boss”的值最小,为1。每个级别的员工的级别都在增加,最高级别为4,而视图是用一个分层查询here构建的。
创建视图后,第一个问题的答案是将所有更高级别的员工相加。对每个列组都执行此操作,联接将信息带到最终视图。
第二个问题是用更野蛮的方式来回答的。一个自我连接,以产生所有可行的员工和老板的组合。在那之后,生产线与最低老板工资。
--Creating a view with the level of the diagram
CREATE VIEW MyCTEView
AS
WITH my_anchor AS (
SELECT boss.[empId], boss.[empName], boss.[mgrId], 1 AS EmpLevel
FROM [MySchema].[dbo].[employee] AS boss
WHERE boss.[mgrId]=boss.[empId]
UNION ALL
SELECT Emp.[empId], Emp.[empName], Emp.[mgrId], EL.EmpLevel+1
FROM [MySchema].[dbo].[employee] AS Emp
INNER JOIN my_anchor as EL
ON Emp.[mgrId] = EL.[empId]
WHERE Emp.[mgrId]<>Emp.[empId]
)
SELECT * FROM my_anchor;
--Answer to the first question
SELECT A.[empName]
,temp.direct_and_indirect-1 AS your_total
FROM [MySchema].[dbo].[MyCTEView] AS A
LEFT JOIN (
SELECT [EmpLevel],SUM(direct_subortinates) OVER(ORDER BY [EmpLevel]) AS direct_and_indirect
FROM (SELECT COUNT([mgrId]) AS direct_subortinates,[EmpLevel]
FROM [MySchema].[dbo].[MyCTEView] GROUP BY [EmpLevel])T) AS Temp
ON Temp.[EmpLevel]=A.[EmpLevel]
ORDER BY A.[empName]
--Answer to the second question. Creating a CTE with all the viable combinations of employee and manager based on criteria.
--Displaying the information for the minimum
WITH cte AS (
SELECT A.[empId] as emId
,A.[empName] as emName
,A.[salary] as emsalary
,A.[EmpLevel] as emLevel
,B.[empId] as bossId
,B.[empName] as bossName
,B.[salary] as bosssalary
,B.[EmpLevel] as bossLevel
FROM [MySchema].[dbo].[MyCTEView] AS A
INNER JOIN
[MySchema].[dbo].[MyCTEView] AS B
ON A.empId<>B.empId AND A.[EmpLevel]>B.[EmpLevel] AND B.[salary]>=2*A.[salary]
)
SELECT tb1.emName, tb1.bossName
FROM cte AS tb1
INNER JOIN
(
SELECT emName, MIN(bosssalary) MinSalary
FROM cte
GROUP BY emName
)tb2
ON tb1.emName=tb2.emName
WHERE tb1.bosssalary=tb2.MinSalary
关于mysql - 对于员工表中的每个员工,在层次结构中找到直接和间接老板的数量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58852294/