简体   繁体   中英

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. Unfortunately there is no separate table for Employee or Staff but a single 'resource' table called ahsresources. The managers are identified with a relation called '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

预期结果

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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