Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating column that resets itself

I have a column consisting of increasing integers (starts at 1 and increases to N). I want to create a second column that runs from 1, 2, 3, 4 then resets and starts at 1, 2, 3, … and so on. Explicitly shown, this is what I desire:

1   1
2   2
3   3
4   4
5   1
6   2
7   3
8   4
9   1
10  2
11  3
12  4
13  1
14  2
15  3
... ...

Do you have a hint as to how I can do this in SQL? Ideally a complete code example?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You may try to number the rows with ROW_NUMBER() and add a simple calculation:

SELECT Column1, ((ROW_NUMBER() OVER (ORDER BY Column1) - 1) % 4) + 1 AS Column2
FROM Yourtable
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading