在SQL中循环行并匹配值
感谢您对我的问题的任何帮助!我有一张所有员工的组织结构图,然后是他们主管的专栏。我试图为每个有3年以上工作经验的员工找到组织结构中的第一位主管。因此,如果主管1只有一年的时间,我将需要转到下一个专栏《超级visor 2》,看看他们是否有更多的经验。最后,我想返回一列主管ID[经验丰富的主管栏] 表:组织结构图在SQL中循环行并匹配值,sql,Sql,感谢您对我的问题的任何帮助!我有一张所有员工的组织结构图,然后是他们主管的专栏。我试图为每个有3年以上工作经验的员工找到组织结构中的第一位主管。因此,如果主管1只有一年的时间,我将需要转到下一个专栏《超级visor 2》,看看他们是否有更多的经验。最后,我想返回一列主管ID[经验丰富的主管栏] 表:组织结构图 id | experience | supervisor_id_1| supervisor_id_2 | experienced_supervisor A |
id | experience | supervisor_id_1| supervisor_id_2 | experienced_supervisor
A | 2 | X | C | X
C | 5 | V | D | D
V | 1 | M | X | M
X | 3
D | 8
M | 11
我是SQL新手,甚至不确定这是否是最好的方法。但我的想法是:我将使用这个案例来审视每一行员工,并比较他们的主管的经验
SELECT CASE
WHEN experience >=3 THEN supervisor_id_1
ELSE
CASE WHEN experience >=3 THEN supervisor_id_2
ELSE 'not found'
END AS experienced_supervisor
FROM org_chart
问题:
这是解决这个问题的最好办法吗?
我可以通过将主管id\u 1、主管id\u 2与id匹配来查找主管的价值[经验年数]吗?或者我是否需要创建一个新的专栏主管\u id\u 1\u经验,并通过加入来填补多年的经验?
我用的是红移 您只需要一个case表达式,但需要大量的联接或子查询。或许
SELECT (CASE WHEN (SELECT oc2.experience >=3 FROM org_chart oc2 WHERE oc2.id = supervisor_id_1) >= 3
THEN supervisor_id_1
WHEN (SELECT oc2.experience >=3 FROM org_chart oc2 WHERE oc2.id = supervisor_id_2) >= 3
THEN supervisor_id_2
. . .
END) AS experienced_supervisor
FROM org_chart oc
经过大量的尝试和错误,这是解决我问题的结果。在这种情况下,我使用的是红移
-- Use common table expression to find job level for each supervisor from reporting levels 8 to 2
WITH cte1 AS
(
SELECT B.id as employee
,B.experience as employee_experience
,B.supervisor_id_1 as manager_1
,A.experience as supervisor_1_experience
FROM org_chart
INNER JOIN org_chart B ON B.supervisor_id_1 = A.id
),
cte2 AS
(
SELECT B.id as employee2
,B.experience as employee_experience
,B.supervisor_id_2 as manager_2
,A.experience as supervisor_2_experience
FROM org_chart
INNER JOIN org_chart B ON B.supervisor_id_2 = A.id
),
........-- Write as many statements as I have columns with reporting levels
-- Join all tables above
cte3 AS
(
SELECT employee
,employee_experience
,manager_1
,supervisor_1_experience
,manager_2
,supervisor_2_experience
FROM cte1
JOIN cte2 ON cte2.employee2 = cte1.employee
....... -- Write as many statements as I have columns with reporting levels
)
-- Run through every row and evaluate if each supervisor has more than 3 years of experience
SELECT *
,CASE
WHEN cte3.supervisor_1_experience >= 3 THEN cte3.manager_1
WHEN cte3.supervisor_1_experience < 3
AND cte3.supervisor_2_experience >=3
THEN cte3.manager_2
........ -- Write as many statements as I have columns with reporting levels
END experienced_supervisor
FROM cte3
用您正在使用的数据库标记您的问题。