I have a table with votes from multiple sectors (think of each sector as a state or similar) on multiple candidates. Each sector has multiple candidates, each with a different vote count.
Here is my table (simplified)
CREATE TABLE [Results]
(
[SectorID] BIGINT,
[CanditateID] BIGINT,
[VoteCount] BIGINT,
[Newness] DATETIME
)
I obviously keep sector and candidate meta data in another table, but I need to find the highest voted candidate for each sector, so I can join those tables into a view.
The best candidate in each sector, is determined by [VoteCount], and if there are two with the same number of votes, it is determined by [Newness]. There must remain exactly one line per sector, and I have to be able to use it in a view, joined together with the meta data.
How do I obtain the highest voted candidate from each sector?
Assuming that you are using SQL Server 2005 or greater, you want to do this with
row_number():