2016-03-09 305 views
1

例如如何生成索引列,如果這裏是基於另一列

Student  Course 
--------------------------- 
student 1 |  Math 
-------------------------- 
student 1 |  English 
-------------------------- 
student 1 |  Art 
-------------------------- 
student 2 |  Math 
-------------------------- 
student 2 |  Economics 
-------------------------- 
student 3 |  Math 
-------------------------- 
student 3 |  English 
-------------------------- 

我想怎麼產生的根據學生的課程索引列,這樣

Student  Course  Index 
-------------------------------------------- 
student 1 |  Math  | 1 
-------------------------------------------- 
student 1 |  English | 2 
-------------------------------------------- 
student 1 |  Art  | 3 
-------------------------------------------- 
student 2 |  Math  | 1 
-------------------------------------------- 
student 2 |  Economics | 2 
-------------------------------------------- 
student 3 |  Math  | 1 
-------------------------------------------- 
student 3 |  English | 2 
-------------------------------------------- 

所以基本上,第二個表的第三列是每個學生的索引/序列,但是我希望第二個表成爲對第二個表(在Oracle中)的查詢,但找不到解決方案。我只能做出總和,而不是索引。

+0

每個學生的課程順序是否重要? –

回答

3

ROW_NUMBER()是你在找什麼

SELECT Student 
     ,Course 
     ,ROW_NUMBER() OVER (PARTITION BY Student ORDER BY Course DESC) AS "Index" 
FROM your_table; 
+0

Afaik你需要引用「索引」,因爲它是一個關鍵字。 –

+0

True @JoachimIsaksson。編輯。 – sqluser

+4

我必須學會更快地輸入.... –

3

您需要使用ROW_NUMBER窗口功能。

select student, course, 
    Row_number() over (partition by student order by course) 
from the_table