反转 'With Recursive' 语句

Reversing a 'With Recursive' statement

我有 ff。查询以显示主管层次结构下的任何人:

 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 等。但我不确定如何。

提前感谢您的任何建议。 :)

只需对现有查询进行少量修改,就可以在单个字段中显示主管的完整层次结构:

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;