Reputation: 13
How can I get the output from the input using Microsoft SQL Server? (Basically select the row per ID where vote is max).
Input
ID Label Vote
-----------------------
79185673 2 3
79185673 0 17
79185724 4 5
79185724 1 13
79185724 0 2
79185900 1 17
79185900 2 1
79185900 4 2
79186190 3 3
79186190 2 17
Output
ID Label Vote
-----------------------
79185673 0 17
79185724 1 13
79185900 1 17
79186190 2 17
Upvotes: 0
Views: 81
Reputation: 11556
Use ROW_NUMBER
or DENSE_RANK
function to give a rank per ID
in the descending order of Vote
column and then select the rows having rank 1.
I prefer DENSE_RANK
function, because it will give same rank for the same Vote
values.
Query
;with cte as(
select [rank] = DENSE_RANK() over(
partition by [ID]
order by [Vote] desc
), *
from [your_table_name]
)
select [ID], [Label], [Vote] from cte
where [rank] = 1;
Upvotes: 4