问题
I want to enumerate rows such that non-unique values get the same number and do not increase. So my data should look like:
id - term_seq_id - rn
---------------------
1 0944 1
1 0944 1
1 0962 2
2 1024 1
2 1054 2
I was looking at this solution:
SQL: enumerate returned rows within each group
Which works if the values are all unique in the ORDER BY
statement in the window function. So I have the following query from this solution but it doesn't work:
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
However this fails to provide the correct output. Instead it does:
id - term_seq_id - rn
---------------------
1 0944 1
1 0944 2
1 0962 3
2 1024 1
2 1054 2
I am at a loss, there doesn't seem to be any way to say "only increment if term_seq_id
increases". I tried partioning by multiple rows but that didn't do anything.
回答1:
Are you looking for this:
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
回答2:
use 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
来源:https://stackoverflow.com/questions/54215523/enumerating-rows-in-sql-with-multiple-same-values