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
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.