ROW_NUMBER() OVER() 分析函式的用法

Allen_liyu發表於2017-08-28

Oracle 中的 ROW_NUMBER() OVER() 分析函式的用法

ROW_NUMBER() OVER(partition by col1 order by col2) 表示根據col1分組,在分組內部根據col2排序,而此函式計算的值就表示每組內部排序後的順序編號(組內是連續且唯一的)。

舉例:

SQL> DESC T1;

Name                                           Null?    Type
----------------------------------------- -------- ----------------------------
ID                                                    NUMBER
NAME                                                    VARCHAR2(10)
DATE1                                                    DATE

SQL> SELECT * FROM T1;
        ID NAME                           DATE1
---------- ------------------------------ ------------------
       101 aaa                                  09-SEP-13

       101 bbb                                  10-SEP-13

       101 ccc                                  11-SEP-13

       102 ddd                                  08-SEP-13

       102 eee                                  11-SEP-13


SQL> SELECT ID,NAME,DATE1,ROW_NUMBER() OVER(partition by ID order by DATE1 desc) as RN FROM T1;

    ID NAME               DATE1               RN
---------- ------------------------------ ------------------ ----------
       101 ccc                  11-SEP-13              1
       101 bbb                  10-SEP-13              2
       101 aaa                  09-SEP-13              3
       102 eee                  11-SEP-13              1
       102 ddd                  08-SEP-13              2


把上面語句作為一個子表語句,嵌入到另一條語句中:


SQL> SELECT ID,NAME,DATE1 FROM (SELECT ID,NAME,DATE1,ROW_NUMBER() OVER(partition by ID order by DATE1 desc) as RN FROM T1)T WHERE T.RN=1;

        ID NAME                           DATE1
---------- ------------------------------ ------------------
       101 ccc                                  11-SEP-13
       102 eee                                  11-SEP-13

轉載自:http://blog.csdn.net/iw1210/article/details/11937085


相關文章