枚举 sql 中具有多个相同值的行

enumerating rows in sql with multiple same values

我想枚举行,使非唯一值获得相同的数字并且不增加。所以我的数据应该是这样的:

id - term_seq_id - rn
---------------------
1    0944          1
1    0944          1
1    0962          2
2    1024          1
2    1054          2

我在看这个解决方案:

如果值在 window 函数的 ORDER BY 语句中都是唯一的,则该方法有效。所以我从这个解决方案中得到以下查询,但它不起作用:

SELECT  student_id_fk
, Term_Seq_Id
, ROW_NUMBER() OVER (PARTITION BY student_id_fk ORDER BY Term_Seq_Id ) AS rn
FROM Courses AS c

ORDER BY student_id_fk, Term_Seq_Id

然而,这无法提供正确的输出。取而代之的是:

id - term_seq_id - rn
---------------------
1    0944          1
1    0944          2
1    0962          3
2    1024          1
2    1054          2

我很茫然,好像没办法说"only increment if term_seq_id increases"。我尝试按多行进行分区,但没有做任何事情。

使用dense_rank()

SELECT  student_id_fk
, Term_Seq_Id
, dense_rank() OVER (PARTITION BY student_id_fk ORDER BY Term_Seq_Id ) AS rn
FROM Courses AS c

ORDER BY student_id_fk, Term_Seq_Id

你在找这个吗:

SELECT  student_id_fk
, Term_Seq_Id
, DENSE_RANK() OVER (PARTITION BY student_id_fk ORDER BY Term_Seq_Id ) AS rn
FROM Courses AS c

ORDER BY student_id_fk, Term_Seq_Id