简体   繁体   English

SQL-基本但仍然觉得它很复杂

[英]SQL- basic but still finding it complicated

I am working on SQL query which should return the list of Managers and the staff who reports to them.我正在处理 SQL 查询,该查询应返回经理列表和向他们报告的员工。 Unfortunately there is no separate table for Employee or Staff but a single 'resource' table called ahsresources.不幸的是,Employee 或 Staff 没有单独的表,只有一个名为 ahsresources 的“资源”表。 The managers are identified with a relation called 'C0'.管理者用称为“C0”的关系来标识。

Even after trying various Joins, I am unable to extract the list.即使在尝试了各种加入之后,我也无法提取列表。 The idea is that a manager will run the report to see his reportees, as well as those staff who report to his own reportees这个想法是,经理将运行报告来查看他的报告者,以及那些向他自己的报告者报告的员工

Example -例子 -

样品表

Now, if lets say HDY is running the query, then its should return him the below result现在,如果假设 HDY 正在运行查询,那么它应该返回以下结果

预期结果

Below is the query I have created, but for the matter of understanding the issue, you can use the above example.下面是我创建的查询,但为了理解问题,您可以使用上面的示例。

 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'

In SQL Server, you can use a recursive query to traverse this hierarchical dataset:在 SQL Server 中,可以使用递归查询来遍历这个分层数据集:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM