在保持行的层次结构的同时对表进行排序

时间:2015-05-27 13:23:32

标签: sql oracle sql-order-by

我有一张代表部门层次结构的表格:

+-----------+--------------+--------------+--------------+-----------+-------+
| Top Dept. | 2-tier Dept. | 3-tire Dept. | 4-tier Dept. |    name   |  tier |
+-----------+--------------+--------------+--------------+-----------+-------+
|        00 |              |              |              |    abc    |   0   |
|           | 00-01        |              |              |    bcd    |   1   |
|           |              | 00-01-01     |              |    cde    |   2   |
|           |              | 00-01-02     |              |    abc    |   2   |
|           | 00-02        |              |              |    aef    |   1   |
|           |              | 00-02-01     |              |    qwe    |   2   |
|           |              | 00-02-03     |              |    abc    |   2   |
|           |              |              | 00-02-03-01  |    abc    |   3   |
+-----------+--------------+--------------+--------------+-----------+-------+

现在我想按名字对同一层中的行进行排序,同时保持整体层次结构,这就是我的期望:

+-----------+--------------+--------------+--------------+-----------+-------+
| Top Dept. | 2-tier Dept. | 3-tire Dept. | 4-tier Dept. |    name   |  tier |
+-----------+--------------+--------------+--------------+-----------+-------+
|        00 |              |              |              |    abc    |   0   |
|           | 00-02        |              |              |    aef    |   1   |
|           |              | 00-02-03     |              |    abc    |   2   |
|           |              | 00-02-01     |              |    qwe    |   2   |
|           | 00-01        |              |              |    def    |   1   |
|           |              | 00-01-02     |              |    abc    |   2   |
|           |              | 00-01-01     |              |    cde    |   2   |
|           |              |              | 00-02-03-01  |    abc    |   3   |
+-----------+--------------+--------------+--------------+-----------+-------+

缺少的数据意味着空,我使用Oracle DB,任何人都可以帮助我吗? 编辑:实际上,它是this sql的简单版本,我试图添加一个新列,该列汇总前四列的值,然后按名称排序,但它确实& #39; t work。

1 个答案:

答案 0 :(得分:1)

更新:这似乎正常...... SQL Fiddle

我原来评论中真正需要的就是在两个选项中按顺序修改名称到部门。这允许引擎首先按名称排序,同时保持层次结构。

WITH cte(Dept, superiorDept, name, depth, sort)AS (
SELECT 
  Dept,
  superiorDept,
  name,
  0,
  name|| dept
FROM hierarchy h
WHERE superiorDept IS NULL

UNION ALL

SELECT 
  h2.Dept,
  h2.superiorDept,
  h2.name,
  cte.depth + 1,
  cte.sort || h2.name ||h2.dept
FROM hierarchy h2
INNER JOIN cte ON h2.superiorDept = cte.Dept
)

SELECT 
  CASE WHEN depth = 0 THEN Dept END AS 一级部门,
  CASE WHEN depth = 1 THEN Dept END AS 二级部门,
  CASE WHEN depth = 2 THEN Dept END AS 三级部门,
  CASE WHEN depth = 3 THEN Dept END AS 四级部门,
  name,
  depth,
  sort
FROM cte
ORDER BY sort, name