0

Oracle11g

无论列的排序顺序如何,我都希望 rownum 按顺序出现(从最小到最大)。我可以通过通过子选择发送查询来实现这一点,如本Query所示。

问题:有没有其他方法可以让 rownum 排序独立于“order by”子句?

with alphabet as
( select 'A' as letters from dual union all
  select 'B' as letters from dual union all 
  select 'C' as letters from dual)
  select rownum, letters from
  (select letters from alphabet
  --    order by  letters -- I can change the sort order here w/o changing rownum sort order.
     order by  letters desc)

如果我不进行子选择,那么我的 rownum 将按列排序,如下所示:

with alphabet as
( select 'A' as letters from dual union all
  select 'B' as letters  from dual union all 
  select 'C' as letters from dual)
  select rownum, letters  from alphabet  
  order by letters desc      -- sorting here alters the rownum sort.
4

1 回答 1

1

使用内联视图有什么缺点?

您始终可以使用row_number分析函数而不是rownum伪列。但这需要你把你的ORDER BY放在两个不同的地方

with alphabet as
( select 'A' as letters from dual union all
  select 'B' as letters  from dual union all
  select 'C' as letters from dual)
select row_number() over (order by letters desc) rn,
       letters
  from alphabet
 order by letters desc

只要您的分析函数ORDER BYORDER BY外部查询中的匹配,无论排序顺序如何,它都有效

SQL> ed
Wrote file afiedt.buf

  1  with alphabet as
  2  ( select 'A' as letters from dual union all
  3    select 'B' as letters  from dual union all
  4    select 'C' as letters from dual)
  5  select row_number() over (order by letters desc) rn,
  6         letters
  7    from alphabet
  8*  order by letters desc
SQL> /

        RN L
---------- -
         1 C
         2 B
         3 A

SQL> ed
Wrote file afiedt.buf

  1  with alphabet as
  2  ( select 'A' as letters from dual union all
  3    select 'B' as letters  from dual union all
  4    select 'C' as letters from dual)
  5  select row_number() over (order by letters asc) rn,
  6         letters
  7    from alphabet
  8*  order by letters asc
SQL> /

        RN L
---------- -
         1 A
         2 B
         3 C
于 2013-02-26T18:28:43.737 回答