OracleSQL -> 按三级排序查看

问题描述 投票:0回答:1

我在Oracle SQL Developer中创建了以下视图。

enter image description here

结果没有按照我需要的方式排序。

我需要像这样对结果进行排序。

enter image description here

所以,如果你把它画成一个深度为3的图,它看起来会是这样的:

![enter image description here

最大深度是三 我尝试了不同的方法 select connect_by_root但它不工作。ORDER BY 也不工作,因为树结构的数据。

有没有人给我一个提示?

sql oracle sql-order-by
1个回答
0
投票

你可以使用 left join:

select t.*
from t left join
     t tp
     on tp.id = t.parent_id
order by coalesce(tp.parent_id, t.parent_id, t.id),
         coalesce(t.parent_id, t.id),
         t.id

这是假设父ID比ID小,这对你的数据来说似乎是真的。 这不是一个必要的假设,但它简化了逻辑。


0
投票

有了 LEFT 自连接和条件排序。

select t1.*
from tablename t1
left join tablename t2 on t2.id = t1.parent_id
order by coalesce(t2.parent_id, t1.parent_id, t1.id),
         case when t1.parent_id is null then 0 else 1 end,
         case when t2.parent_id is not null then t1.parent_id else t1.id end,
         case when t2.parent_id is null then 0 else 1 end,
         t1.id

参见 演示. 结果。

>     ID | PARENT_ID | LEVEL    
> -----: | --------: | :--------
>  29101 |      null | LVL_ONE  
> 153799 |     29101 | LVL_TWO  
> 153800 |    153799 | LVL_THREE
> 153801 |    153799 | LVL_THREE
> 153803 |     29101 | LVL_TWO  
> 153804 |    153803 | LVL_THREE
> 153802 |      null | LVL_ONE  
> 153805 |    153802 | LVL_TWO  
> 153806 |    153805 | LVL_THREE

0
投票

如果你所使用的视图是一个分层查询,那么你有一个选项 "排序兄弟姐妹",我建议你使用该选项。

下面是一个例子https:/oracle-base.comarticlesmischierarchical-queries。


0
投票
drop table a1;

CREATE TABLE a1
as 
SELECT 153804 as ID, 153803 as PARENT_ID
FROM DUAL
UNION ALL
SELECT 153801, 153799
FROM DUAL
UNION ALL
SELECT 153803, 29101
FROM DUAL
UNION ALL
SELECT 29101, NULL
FROM DUAL
UNION ALL
SELECT 153802, NULL
FROM DUAL
UNION ALL
SELECT 153805, 153802
FROM DUAL
UNION ALL
SELECT 153806, 153805
FROM DUAL
UNION ALL
SELECT 153800, 153799
FROM DUAL
UNION ALL
SELECT 153799, 29101
FROM DUAL
;


select id, parent_id, level, 'LEVEL_' || level as level_desc
from a1
start with parent_id is null
connect by parent_id = prior(id)
order siblings by id
;
© www.soinside.com 2019 - 2024. All rights reserved.