【发布时间】:2019-08-06 00:57:38
【问题描述】:
我有一个包含父行和子行的结果集。 (子行永远不会有子行)。 我需要对其进行分页(考虑到排序),以便:
首先需要在分页页面上只选择父母(例如,当页面大小= 10时,它必须包含
源结果集如下所示:
+----+-----------+-------------+
| ID | PARENT_ID | SORT_COLUMN |
+----+-----------+-------------+
| 1 | | y |
| 2 | 1 | z |
| 3 | | u |
| 4 | | q |
| 5 | 4 | o |
| 6 | 4 | p |
| 7 | | c |
+----+-----------+-------------+
~期望的结果:
+----+-----------+-------------+----+----------+
| ID | PARENT_ID | SORT_COLUMN | RN | RN_CHILD |
+----+-----------+-------------+----+----------+
| 7 | | c | 1 | |
| 4 | | q | 2 | |
| 5 | 4 | o | 2 | 1 |
| 6 | 4 | p | 2 | 2 |
| 3 | | u | 3 | |
| 1 | | y | 4 | |
| 2 | 1 | z | 4 | 1 |
+----+-----------+-------------+----+----------+
现在我是这样做的:
with
cte as
(select 1 as id, null as parent_id, 'y' as sort_column from dual
union all
select 2 as id, 1 as parent_id, 'z' as sort_column from dual
union all
select 3 as id, null as parent_id, 'u' as sort_column from dual
union all
select 4 as id, null as parent_id, 'q' as sort_column from dual
union all
select 5 as id, 4 as parent_id, 'o' as sort_column from dual
union all
select 6 as id, 4 as parent_id, 'p' as sort_column from dual
union all
select 7 as id, null as parent_id, 'c' as sort_column from dual)
select
*
from
(select
t.*,
dense_rank() over (order by
case when t.parent_id is null
then
t.sort_column
else
(select t2.sort_column from cte t2 where t2.id = t.parent_id)
end) as RN,
case
when parent_id is null
then
null
else
row_number() over (partition by t.parent_id order by t.sort_column)
end as RN_CHILD
from cte t)
--where RN between :x and :y
order by RN, RN_CHILD nulls first
但我认为这可以在不需要额外访问结果集的情况下完成。 (select t2.sort_column from cte t2 where t2.id = t.parent_id)。
怎么做?
UPD:父母必须按sort_column排序,父母内的孩子也必须按sort_column排序。
【问题讨论】:
标签: sql oracle pagination hierarchical-data window-functions