我有一个至少有三列的表,EMPLID,NAME,SUPERVISOR_ID。在一个查询中,我希望得到一个经理直接报告,包括从下属管理员到WHERE
条款中给出一个managerid的最低人员的直接报告。
我可以创建一个查询,显示谁向谁报告:
SELECT MANAGER.[EMPLID] AS MANAGEREMPLID, MANAGER.[NAME], MANAGER.[SUPERVISOR_ID], STAFF.[EMPLID] AS STAFFEMPLID, STAFF.[NAME], STAFF.[SUPERVISOR_ID]
FROM MYHRTABLE AS MANAGER INNER JOIN MYHRTABLE AS STAFF
ON MANAGER.[EMPLID] = STAFF.[SUPERVISOR_ID]
ORDER BY MANAGER.[NAME], STAFF.[NAME]
或递归CTE似乎做同样的事情
WITH MYCTE
AS (
SELECT [EMPLID], [NAME],[SUPERVISOR_ID] FROM
(SELECT [EMPLID], [NAME],
CASE WHEN [EMPLID] = [SUPERVISOR_ID] THEN NULL ELSE [SUPERVISOR_ID] END AS [SUPERVISOR_ID]
FROM MYHRTABLE) AS MYDATA
WHERE [SUPERVISOR_ID] IS NULL
UNION ALL
SELECT MYDATA.[EMPLID], MYDATA.[NAME],MYDATA.[SUPERVISOR_ID] FROM
(SELECT [EMPLID], [NAME],
CASE WHEN [EMPLID] = [SUPERVISOR_ID] THEN NULL ELSE [SUPERVISOR_ID] END AS [SUPERVISOR_ID]
FROM MYHRTABLE) AS MYDATA INNER JOIN MYCTE ON MYDATA.[SUPERVISOR_ID] = MyCTE.[EMPLID]
WHERE MYDATA.[SUPERVISOR_ID] IS NOT NULL)
SELECT * FROM MyCTE
(案例陈述是因为最高经理有主管领域向自己报告)
我所寻找的是能够为这个查询提供一个问题,并一直看到向该经理报告的员工。在我的两个例子中,我觉得我可以看到直接报告,但不知怎的,我应该再做一次加入以查看其余的信息。
第二个问题是相关的,在研究这个问题时,似乎大多数人在使用递归cte找到管理者直接报告时,我认为它可以使用加入自身的第一个查询来解决。鉴于我发布的两个查询,为什么我可以使用递归CTE来解决它,当我可以使用相同的表连接到自己?好像我得到了同样的信息?
如果它意味着什么,这将在SQL Server 2012或2008上运行。
答案 0 :(得分:4)
使用递归的原因是能够通过递归更改为用作锚点的管理器向下钻取数据,直到找不到更多内容并将输出作为层次结构。
连接查询将限制为每个连接一个级别(尝试添加with src as (
select
[emplid]
, [name]
, case
when [emplid] = [supervisor_id] then null
else [supervisor_id]
end as [supervisor_id]
from myhrtable
), cte as (
select [emplid], [name], [supervisor_id], [emplid] as top_manager
from src
where [emplid] = 1 -- this is the manager you're interested in
-- it can be a sub-manager in the middle or the tree
union all -- or the top level manager rooting the tree
select src.[emplid], src.[name], src.[supervisor_id], top_manager
from src
inner join cte on src.[supervisor_id] = cte.[emplid]
where src.[emplid] <> top_manager
)
select * from cte
(或w / e经理的id)并观察发生的情况)。如果您事先知道级别数,则可以使用左连接(每个级别有一个连接)。
我会改变递归解决方案:
am = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> list = am.getRunningAppProcesses();