【问题标题】:Reversing a 'With Recursive' statement反转“With Recursive”语句
【发布时间】:2016-02-22 13:30:11
【问题描述】:

我有 ff。查询以显示 Director's Hierarchy 下的任何人:

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

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

【问题讨论】:

  • 您是否真的需要为每个主管级别设置一个单独的列,或者将主管的完整层次结构放在每个员工的单个(逗号分隔?)字段中是否可以接受?
  • 可以接受。 :) ,无论如何我都可以用 PHP 来安排它们

标签: sql postgresql common-table-expression recursive-query


【解决方案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;

【讨论】:

  • 您可以使用concat_ws(',', e.current_sup_name, t.current_sup_name) 而不是||,它可以正确处理null 值或空字符串。
猜你喜欢
  • 1970-01-01
  • 2017-04-17
  • 1970-01-01
  • 2018-10-09
  • 2017-01-16
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多