簡體   English   中英

SQL-基本但仍然覺得它很復雜

[英]SQL- basic but still finding it complicated

我正在處理 SQL 查詢,該查詢應返回經理列表和向他們報告的員工。 不幸的是,Employee 或 Staff 沒有單獨的表,只有一個名為 ahsresources 的“資源”表。 管理者用稱為“C0”的關系來標識。

即使在嘗試了各種加入之后,我也無法提取列表。 這個想法是,經理將運行報告來查看他的報告者,以及那些向他自己的報告者報告的員工

例子 -

樣品表

現在,如果假設 HDY 正在運行查詢,那么它應該返回以下結果

預期結果

下面是我創建的查詢,但為了理解問題,您可以使用上面的示例。

 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 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