Nikolas
Nikolas

Reputation: 44368

SQL, get max id of column

I've got this table in MS SQL Server Management Studio

+------+-----------+--------
| id   | client id | bla bla blaaaa
+------+-----------+--------
|    1 |   1       | .......
|    2 |   2       | .......
|    3 |   3       | .......
|    4 |   8       | .......
|    5 |   9       | .......
|    6 |   15      | .......
|    7 |   1       | .......
|    8 |   16      | .......
|    9 |   2       | .......
|   10 |   9       | .......
|   12 |   12      | .......
+------+-----------+--------

I need to get unique [client id] with max value of [id], like this

+------+-----------+--------
| id   | client id | bla bla blaaaa
+------+-----------+--------
|    3 |   3       | .......
|    4 |   8       | .......
|    6 |   15      | .......
|    7 |   1       | .......
|    8 |   16      | .......
|    9 |   2       | .......
|   10 |   9       | .......
|   12 |   12      | .......
+------+-----------+--------

I tried this code, but it doesn't work well .. can someone help me?

SELECT *
FROM   table AS one 
INNER JOIN table AS two
   ON one.[client id] = two.[client id]
   WHERE one.[id] > two.[id]

Upvotes: 2

Views: 36627

Answers (2)

Evaldas Buinauskas
Evaldas Buinauskas

Reputation: 14077

I'd go for ROW_NUMBER() solution:

SELECT *
FROM (
    SELECT ROW_NUMBER() OVER(PARTITION BY [client id] ORDER BY [id] DESC) AS RN, *
    FROM table AS one
    ) AS T
WHERE T.RN = 1;

Upvotes: -1

nick
nick

Reputation: 693

SELECT max(id), client_id, blah_blah
FROM my_table
GROUP BY client_id, blah_blah

Upvotes: 12

Related Questions