Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment Row_Number Only Where Distinct

Tags:

t-sql

I have the following table, which I've made very simple because I do not know how to format it as a table on here (side note if anyone could link me to an easy tutorial on that I would be forever grateful).

id
1
1
1
2
2
2

I'd like to add another column which increments in number only on distinct IDs so the outcome should be

Id
1
1
1
2
2
2

rowNum 
1
1
1
2
2
2

Currently all I can manage to get is:

id
1
1
1
2
2
2
rowNum
1
2
3
4
5
6

I'm missing something very simple here as I'm confident I should be able to solve this issue using either row_number or rank and a window function but I cannot figure it out.

like image 928
MPJ567 Avatar asked Nov 29 '25 01:11

MPJ567


1 Answers

Use DENSE_RANK() instead of ROW_NUMBER():

SELECT
    id,
    DENSE_RANK() OVER (ORDER BY id) dr
FROM yourTable

Demo

like image 97
Tim Biegeleisen Avatar answered Dec 02 '25 06:12

Tim Biegeleisen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!