erickalves05
erickalves05

Reputation: 273

How to SELECT the last distinct record in SQL SERVER

So, I have this table:

|  COD   | |   ID   |  |BALANCE|   |         DATE          |

 20002978   34134987      2,1       2012-10-20 00:00:00.000
 20002978   34134987      2,1       2012-10-30 00:00:00.000
 20002978   34134987      10,1      2012-12-05 00:00:00.000
 20002978   34134987      8,1       2012-12-22 00:00:00.000
 20002978   34134987      9,1       2013-01-16 00:00:00.000
 20002978   34134987      23,1      2013-01-19 00:00:00.000
 20002978   34134987      7,1       2013-01-29 00:00:00.000
 20002978   34134987      3,1       2013-02-02 00:00:00.000
 80125573   34134987      13,1      2013-02-22 00:00:00.000
 80125573   34134987      1,0       2013-03-08 00:00:00.000

I want to select the last balance of the last code where the ID is the parameter that I'll pass to the procedure.

I need something like this as the result:

ID = 34134987

|  COD   | |   ID   |  |BALANCE|   |         DATE          |
 20002978   34134987      3,1       2013-02-02 00:00:00.000
 80125573   34134987      1,0       2013-03-08 00:00:00.000

Any tips? Thanks in advance.

Upvotes: 3

Views: 2023

Answers (1)

Amit Singh
Amit Singh

Reputation: 8109

Try like this.....

Select  Cod,Id,Balance,[Date] from (
Select Row_Number() Over(Partition By Cod,Id Order By [Date] desc) as Row, Cod,Id,Balance,Date
from table) t where t.Row=1

Upvotes: 3

Related Questions