Share via

Running count column

nd0911 86 Reputation points
2022-03-30T15:13:31.917+00:00

Hello,

I have a simple table with few column, one of the column is FK ID that (of course) can repeat it self more then one time in the table.
I want to create a Select Query that select this FK ID and base on this column will add additional column with running count start from 1 that every unique FK ID will add one more.

To keep things simple, this is my select query:

    SELECT 
            T.FK
             ------>here need the additional column with the running number
    FROM 
          Tbl T
   ORDER BY
          T.FK

The resulte I'm expecting is this:

 T.FK         Additional Col
-----------------------------
275               1
275               1
275               1
303               2
303               2
309               3
309               3
309               3
309               3
350               4
400               5
400               5

What do I need to add to my query to get this additional column ?

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

Tom Cooper 8,501 Reputation points
2022-03-30T15:40:28.187+00:00

Select T.FK, Dense_Rank() Over(Order By T.FK) As NewColumn
From Tbl T;

Tom

Was this answer helpful?

2 people found this answer helpful.
0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Guoxiong 8,221 Reputation points
    2022-03-30T15:25:25.187+00:00

    Try this:

    ;WITH CTE AS (
        SELECT *, ROW_NUMBER() OVER(ORDER BY FK) AS AdditionalCol
        FROM (
            SELECT FK 
            FROM Tbl
            GROUP BY FK
        ) AS t
    )
    
    SELECT T.FK, C.AdditionalCol
    FROM Tbl AS T
    INNER JOIN CTE AS C ON T.FK = C.FK;
    

    Was this answer helpful?

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.