如何在Oracle中反转SELECT语句的结果行顺序?
反转Oracle查询结果行顺序的解决方案
嘿,这个需求很常见!要把查询结果的行完全反转显示,核心是得先保留原始的行顺序,再倒过来排序——毕竟你的示例里原始结果不是按ID或其他字段有序排列的,直接用ORDER BY ID DESC肯定达不到你要的效果。
给你一个简单直接的实现方法,用行号来标记原始顺序,再逆序输出:
with table1 as ( select 1 ID, 'txt1' value from dual union all select 2, 'txt2' from dual union all select 7, 'txt7' from dual union all select 5, 'txt5' from dual union all select 3, 'txt3' from dual ), -- 给每一行分配原始顺序的行号 ordered_table as ( select t.*, row_number() over (order by null) as row_num from table1 t ) -- 按行号倒序查询,得到反转结果 select ID, VALUE from ordered_table order by row_num desc;
代码说明:
row_number() over (order by null):在Oracle中,order by null会保留查询的自然返回顺序(也就是你union all拼接的顺序),这样生成的row_num就对应了原始结果的行位置。- 外层查询通过
order by row_num desc,就能把行顺序完全反转过来。
执行这段SQL后,你会得到想要的结果:
| VALUE |
|---|
| txt3 |
| txt5 |
| txt7 |
| txt2 |
| txt1 |
如果你的原始查询本身是基于某个字段排序的(比如原本是按ID升序),只需要把order by null换成对应的排序字段即可,比如row_number() over (order by ID),再倒序就好。
内容的提问来源于stack exchange,提问作者Nwn
相关产品推荐
相关产品推荐

