Gleb
Gleb

Reputation: 1432

Add order column into query result in SQL Server

I have a table, called Table1 that looks like:

id|val1|val2|FKId
------------------
 1|val |val | 123
 2|val |val | 123
 3|val |val | 234
 4|val |val | 345

I'm using:

SELECT * FROM Table1

I need to add to the result of this query, a column that will contain the order number for each row by FKId. Result that I need looks like:

id|val1|val2|FKId |Order
------------------------
 1|val |val | 123 | 1
 2|val |val | 123 | 1
 3|val |val | 234 | 2
 4|val |val | 345 | 3   

Maybe there is some function in SQL Server to get this?

Upvotes: 0

Views: 90

Answers (1)

Pரதீப்
Pரதீப்

Reputation: 93694

Using Ranking function Dense_Rank() you can get the required order. To know more about Dense_rank check here.

SELECT *,
       Dense_Rank()
         OVER (
           PARTITiON BY val1
           ORDER BY fkid) [Order]
FROM   tablename 

Upvotes: 2

Related Questions