0

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

1 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

If this answer helped you please consider accepting it. Accepting answers rewards the contributor for their effort and helps others to find a working solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.