DENSE_RANK()欺骗Oracle

时间:2017-08-03 22:37:19

标签: sql oracle

我对DENSE_Rank函数感到困惑

所以我有这样的代码

select ID, date
From TABLE1
order by date

所以它像这样执行

ID  DATE
1   10/25/2016
1   10/23/2015
1   10/22/2014
2   10/11/2015
2    5/24/2014
2    5/21/2014
2    3/23/2013
3   10/21/2016
3    9/20/2015

我的代码是

    select ID, Extract(MONTH FROM DATE), DENSE_RANK () OVER (PARTITION BY ID,Extract(MONTH FROM DATE order by DATE) rank
FROM TABLE

显示

   ID  DATE RANK
    1   10  1
    1   10  2
    1   10  3
    2   10  1 
    2    5  1
    2    5  2
    2    3  1
    3   10  1
    3    9  2

但我想表现如下

  ID  DATE RANK
    1   10  1
    1   10  1
    1   10  1
    2   10  1 
    2    5  2
    2    5  2
    2    3  3
    3   10  1
    3    9  2

我如何编码执行上面的

非常感谢

1 个答案:

答案 0 :(得分:3)

您希望按月(按降序排序)排序,而不是按照它们进行分区:

SELECT ID,
       Extract(MONTH FROM "DATE"),
       DENSE_RANK () OVER ( PARTITION BY ID
                            ORDER BY Extract(MONTH FROM "DATE") DESC ) rank
FROM   your_table