2016-02-22 50 views
1

我有ff。查詢顯示董事的層次結構下,任何人:逆轉'With Recursive'語句

WITH RECURSIVE emptree AS (
     SELECT e.win_id, 
      e.full_name, 
      e.current_sup_name, 
      e.sbu, 
      e.cost_center, 
      e.lob, 
      0 AS depth 
      FROM app_reports.vw_hiearchy e 
      WHERE e.win_id = xxxxxxx AND e.attrition_date IS NULL 
     UNION ALL 
     SELECT e.win_id, 
      e.full_name, 
      e.current_sup_name, 
      e.sbu, 
      e.cost_center, 
      e.lob, 
      t.depth + 1 AS depth 
      FROM app_reports.vw_hiearchy e 
      JOIN emptree t ON t.win_id = e.current_sup_win 
      WHERE e.attrition_date IS NULL 
     ) 
SELECT emptree.win_id, 
    emptree.full_name, 
    emptree.current_sup_name, 
    emptree.sbu, 
    emptree.cost_center, 
    emptree.lob, 
    emptree.depth 
    FROM emptree; 

,直到我請求增加另一個列(或以上),以顯示誰是一個特定的監督員(技術上添加列動態監事它工作正常 - 如果可能的話,那從下往上顯示所有主管)。我不確定是否需要顛倒這一點,才能從底層開始實際獲取層次結構,並將其顯示爲current_sup_name_2,current_sup_name3等等。但我不知道如何。

在此先感謝您的任何建議。 :)

+0

你確實需要管理者的每一層單獨的列,或將每個員工的完整層級的監督者放在一個單獨的(逗號分隔?)字段中是否可以接受? –

+0

這是可以接受的。 :),我可以用PHP安排它們 – Odinovsky

回答

1

應該可以顯示監事單場中完整的層次有一個小的修改現有的查詢:

WITH RECURSIVE emptree AS (
     SELECT e.win_id, 
      e.full_name, 
      e.current_sup_name, 
      e.sbu, 
      e.cost_center, 
      e.lob, 
      0 AS depth 
      FROM app_reports.vw_hiearchy e 
      WHERE e.win_id = xxxxxxx AND e.attrition_date IS NULL 
     UNION ALL 
     SELECT e.win_id, 
      e.full_name, 
      concat_ws(',', e.current_sup_name, t.current_sup_name) current_sup_name, 
      e.sbu, 
      e.cost_center, 
      e.lob, 
      t.depth + 1 AS depth 
      FROM app_reports.vw_hiearchy e 
      JOIN emptree t ON t.win_id = e.current_sup_win 
      WHERE e.attrition_date IS NULL 
     ) 
SELECT emptree.win_id, 
    emptree.full_name, 
    emptree.current_sup_name, 
    emptree.sbu, 
    emptree.cost_center, 
    emptree.lob, 
    emptree.depth 
    FROM emptree; 
+2

你可以使用'concat_ws(',',e.current_sup_name,t.current_sup_name)'而不是'''正確處理null值或空字符串。 –

+0

謝謝你! :) – Odinovsky

+0

@jtejido:不客氣! :) –