2013-02-26 199 views
0

Oracle11g的如何在更改另一列排序順序時保持rownum排序順序?

我想ROWNUM出現在順序(從小到大),而不管列的排序順序。我可以通過通過子選擇發送查詢來實現此目的,如查詢所示。

問題:是否有任何其他的方式來保持排序的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 
    (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. 

回答

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 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 
+0

尼斯ORDER BY匹配工作的排序順序不分...如果我有一個更復雜的查詢,按'A,B,C,D,E排序',並且想在其上添加一個row_number(),那麼我需要確保row_number()部分鏡像查詢排序。 。例如'row_number()over(按A,B,C,D,E排序)..right? – zundarz 2013-02-26 18:47:44

+0

@zundarz - 正確。 – 2013-02-26 18:48:09