I have a query which returns to me results as follows:
Race | Candidate | Total Votes | MaxNoOfWinners
---------------------------------------------------
1 | 1 | 5000 | 3
1 | 2 | 6700 | 3
2 | 1 | 100 | 3
2 | 2 | 200 | 3
2 | 3 | 300 | 3
2 | 4 | 400 | 3
...
I was wondering if there was a query that could be written to return only the winners (based on the MaxNoOfWinners and TotalVotes) for a certain race. So for the above i would only get back
Race | Candidate | Total Votes | MaxNoOfWinners
---------------------------------------------------
1 | 1 | 5000 | 3
1 | 2 | 6700 | 3
2 | 2 | 200 | 3
2 | 3 | 300 | 3
2 | 4 | 400 | 3
...
Here is a solution… I did not test so there may be typos. The idea is is use the RANK() function of SQL Server to give a ranking by Race based on votes and not include those that don’t meet the criteria. Note, using RANK() and not ROW_NUMBER() will include ties in the result.