SQL- 基本但仍然觉得它很复杂
SQL- basic but still finding it complicated
我正在处理 SQL 查询,该查询应该 return 经理和向他们报告的员工列表。
不幸的是,没有单独的 table 用于 Employee 或 Staff,而是一个名为 ahsresources 的 'resource' table。
经理使用名为 'C0'.
的关系进行标识
即使尝试了各种连接,我也无法提取列表。这个想法是,经理将 运行 报告以查看他的下属,以及向他自己的下属报告的员工
例子-
现在,如果假设 HDY 正在 运行 查询,那么它应该 return 他下面的结果
下面是我创建的查询,但是为了理解问题,您可以使用上面的例子。
select a.description as manager1,a.rel_value as MGID,a.resource_id as Reportee1_MGR2,r.name,a.date_to as date, r.date_to,a1.resource_id as MG3ID,r1.name as Rep3Name,
a2.resource_id as MG4ID,r2.name as Rep4Name
from ahsrelvalue a
LEFT OUTER JOIN ahsresources r
ON r.resource_id = a.resource_id and r.client = a.client and a.date_to='12/31/2099'
LEFT OUTER JOIN ahsrelvalue a1
ON a1.rel_Value = a.resource_id and a1.client = a.client and a1.date_to = '12/31/2099'
LEFT OUTER JOIN ahsrelvalue a2
ON a2.rel_Value = a1.resource_id and a2.client = a1.client and a2.date_to = '12/31/2099'
LEFT OUTER JOIN ahsresources r1
ON r1.resource_id = a1.resource_id and r1.client = a1.client and a1.date_to='12/31/2099'
LEFT OUTER JOIN ahsresources r2
ON r2.resource_id = a2.resource_id and r2.client = a2.client and a2.date_to='12/31/2099'
where a.rel_Value = '$?resid' and a.rel_attr_id='C0' and r.date_to = '12/31/2099' and r1.date_to ='12/31/2099'
and r.status !='C' and r1.status!='C' and r2.status!='C'
在SQL服务器中,您可以使用递归查询来遍历这个分层数据集:
with cte as (
select t.* from mytable where managerID = 6
union all
select t.*
from cte c
inner join mytable t on t.managerID = c.staffID
)
select * from cte
我正在处理 SQL 查询,该查询应该 return 经理和向他们报告的员工列表。 不幸的是,没有单独的 table 用于 Employee 或 Staff,而是一个名为 ahsresources 的 'resource' table。 经理使用名为 'C0'.
的关系进行标识即使尝试了各种连接,我也无法提取列表。这个想法是,经理将 运行 报告以查看他的下属,以及向他自己的下属报告的员工
例子-
现在,如果假设 HDY 正在 运行 查询,那么它应该 return 他下面的结果
下面是我创建的查询,但是为了理解问题,您可以使用上面的例子。
select a.description as manager1,a.rel_value as MGID,a.resource_id as Reportee1_MGR2,r.name,a.date_to as date, r.date_to,a1.resource_id as MG3ID,r1.name as Rep3Name,
a2.resource_id as MG4ID,r2.name as Rep4Name
from ahsrelvalue a
LEFT OUTER JOIN ahsresources r
ON r.resource_id = a.resource_id and r.client = a.client and a.date_to='12/31/2099'
LEFT OUTER JOIN ahsrelvalue a1
ON a1.rel_Value = a.resource_id and a1.client = a.client and a1.date_to = '12/31/2099'
LEFT OUTER JOIN ahsrelvalue a2
ON a2.rel_Value = a1.resource_id and a2.client = a1.client and a2.date_to = '12/31/2099'
LEFT OUTER JOIN ahsresources r1
ON r1.resource_id = a1.resource_id and r1.client = a1.client and a1.date_to='12/31/2099'
LEFT OUTER JOIN ahsresources r2
ON r2.resource_id = a2.resource_id and r2.client = a2.client and a2.date_to='12/31/2099'
where a.rel_Value = '$?resid' and a.rel_attr_id='C0' and r.date_to = '12/31/2099' and r1.date_to ='12/31/2099'
and r.status !='C' and r1.status!='C' and r2.status!='C'
在SQL服务器中,您可以使用递归查询来遍历这个分层数据集:
with cte as (
select t.* from mytable where managerID = 6
union all
select t.*
from cte c
inner join mytable t on t.managerID = c.staffID
)
select * from cte