2012-07-09 54 views
3

我在Oracle中對某些專欄進行排名時遇到了一些問題。我有兩列我需要排名 - 一個組ID和日期。多個字段的Oracle排名專欄

我想組表兩種方式:

  1. 排名在每個GROUP_ID記錄由DATETIME(RANK_1)
  2. 排名的GROUP_IDs通過DATETIME,GROUP_ID(RANK_2)

它應該看起來像這樣:

GROUP_ID | DATE | RANK_1 | RANK_2 
----------|------------|-----------|---------- 
    2  | 1/1/2012 |  1 | 1 
    2  | 1/2/2012 |  2 | 1 
    2  | 1/4/2012 |  3 | 1 
    3  | 1/1/2012 |  1 | 2 
    1  | 1/3/2012 |  1 | 3 

我已經能夠做到前者,但是哈我一直無法弄清楚後者。

SELECT group_id, 
     datetime, 
     ROW_NUMBER() OVER (PARTITION BY group_id ORDER BY datetime) AS rn, 
     DENSE_RANK() OVER (ORDER BY group_id) AS rn2 
FROM  table_1 
ORDER BY group_id; 

此錯誤定購RANK_2領域:

GROUP_ID | DATE | RANK_1 | RANK_2 
----------|------------|-----------|---------- 
    1  | 1/3/2012 |  1  | 1 
    2  | 1/1/2012 |  1  | 2 
    2  | 1/2/2012 |  2  | 2 
    2  | 1/4/2012 |  3  | 2 
    3  | 1/1/2012 |  1  | 3 
+0

第一種方式與第二種方式有什麼不同,因爲在這兩種情況下,組ID的分區? – Chandu 2012-07-09 17:58:18

回答

3

假設你沒有在表中的實際id列,看來你想要做的最早的日期在第二級每組。這將需要嵌套的子查詢:

select group_id, datetime, rn, 
     dense_rank() over (order by EarliestDate, group_id) as rn2 
from (SELECT group_id, datetime, 
      ROW_NUMBER() OVER (PARTITION BY group_id ORDER BY datetime) AS rn, 
      min(datetime) OVER (partition by group_id) as EarliestDate 
     FROM table_1 
    ) t 
ORDER BY group_id; 
+0

就是這樣!謝謝 – 2012-07-09 18:17:36