Skip to content
Advertisement

Add ‘iteration number’ column to SQL Select based on same values from two columns

I have a SQL (SQL Server) statement SELECT id, animalId, ownerId FROM myTable ORDER BY id which outputs the following data:

What I want to be able to do is add a fourth column dynamically that acts as a counter for each row that has the same values for animalId and ownerId. So the resultant output would be:

Could anyone advise how to go about this please?

Many thanks.

Advertisement

Answer

You can do it with window function ROW_NUMBER():

See the demo.
Results:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement