章節排序問題

regonly1發表於2012-08-21

章節排序問題
我們知道,一般篇幅較大的書籍,都分為很多章,每章下又有很多節,還有小節等。其層次的關係都是以這種方式來表達的:
1
1.1
1.1.1
...
2
2.1
每個數值之間由點分隔。要對其按照正常的章節順序做排序。
假設如下資料:
SQL> select * from t;
 
COL
---------------------------------------------------------------------------
1.2.5
1.2.10
1.10.1
1.2.4
1.10.2
2
1
1.1
2.1
22.333.1
1.1.1
1.1.2
1.2
 
13 rows selected
常見的方法是先將字串中的數字按照點分別取出來,然後依次對其排序。
但其限制也很明顯,就是隻能固定分段數,對於變化的情況處理會出現問題。
如下:
select * from t
 order by regexp_substr(col, '([^.]+)',1,1),
          regexp_substr(col, '([^.]+)',1,2),
          regexp_substr(col, '([^.]+)',1,3)
在tom的blog上看到一遍短文,介紹了另一種方法。其原理是利用字串的
排序方式。固定長度排序,如下:
001
002
010
所以,只要對分段中的每個數值都給予固定長度,補足者補0,這樣就能滿足
此類排序要求。現在以固定長度8作為例子:
select col, regexp_replace(replace('.'||col, '.', '.00000000'), '0+([^\.]{8})', '\1') from t
 order by regexp_replace(replace('.'||col, '.', '.00000000'), '0+([^\.]{8})', '\1')
排序結果如下:

SQL> select col, regexp_replace(replace('.'||col, '.', '.00000000'), '0+([^\.]{8})', '\1') from t
  2   order by regexp_replace(replace('.'||col, '.', '.00000000'), '0+([^\.]{8})', '\1')
  3  /
 
COL                                                                         REGEXP_REPLACE(REPLACE('.'||CO
--------------------------------------------------------------------------- --------------------------------------------------------------------------------
1                                                                           .00000001
1.1                                                                         .00000001.00000001
1.1.1                                                                       .00000001.00000001.00000001
1.1.2                                                                       .00000001.00000001.00000002
1.2                                                                         .00000001.00000002
1.2.4                                                                       .00000001.00000002.00000004
1.2.5                                                                       .00000001.00000002.00000005
1.2.10                                                                      .00000001.00000002.00000010
1.10.1                                                                      .00000001.00000010.00000001
1.10.2                                                                      .00000001.00000010.00000002
2                                                                           .00000002
2.1                                                                         .00000002.00000001
22.333.1                                                                    .00000022.00000333.00000001
 
13 rows selected

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12932950/viewspace-741448/,如需轉載,請註明出處,否則將追究法律責任。

相關文章