SQL Query在比赛中找到获胜者

时间:2011-05-23 20:34:52

标签: sql sql-server-2008

我有一个查询返回给我的结果如下:

  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
    ...

我想知道是否有可以编写的查询只返回某场比赛的获胜者(基于MaxNoOfWinners和TotalVotes)。所以对于上面我只会回来

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
...

3 个答案:

答案 0 :(得分:6)

这是一个解决方案......我没有测试,所以可能存在拼写错误。我们的想法是使用SQL Server的RANK()函数根据投票给出Race的排名,而不包括那些不符合标准的排名。注意,使用RANK()而不是ROW_NUMBER()将在结果中包含关系。

WITH RankedResult AS
(
  SELECT Race, Candidate, [Total Votes], MaxNoOfWinners, RANK ( )  OVER (PARTITION BY Race ORDER BY [Total Votes] DESC) AS aRank
  FROM Results
)
SELECT Race, Candidate, [Total Votes], MaxNoOfWinners
FROM RankedResult
WHERE aRANK <= MaxNumberOfWinners

答案 1 :(得分:2)

这是一个完整的工作样本,假设有两个表竞争和候选

Create Table #Race(Race_id int , MaxNoOfwinners int ) 

INSERT INTO #Race (Race_id , MaxNoOfwinners)
VALUES (1,3), 
       (2,3),
       (3,1)


CREATE TABLE #Candidate (CandidateID int , Race_ID int , Total_Votes int )
INSERT INTO #Candidate (CandidateID  , Race_ID  , Total_Votes  )
VALUES (1,1,5000),
        (2,1,6700),
        (1,2,100),
        (2,2,200),
        (3,2,300),       
        (4,2,400),        
        (1,3,42),
        (2,3,22)


;WITH CTE as (
SELECT 
    RANK() OVER(PARTITION BY race_id ORDER BY  race_id, total_votes DESC ) num,
    CandidateID  , Race_ID  , Total_Votes
From 
    #Candidate)
SELECT * FROM cte inner join #Race r
on CTE.Race_ID = r.Race_id
and num <= r.MaxNoOfwinners

DROP TABLE #Race
DROP TABLE #Candidate

具有以下结果

num                  CandidateID Race_ID     Total_Votes Race_id     MaxNoOfwinners
-------------------- ----------- ----------- ----------- ----------- --------------
1                    2           1           6700        1           3
2                    1           1           5000        1           3
1                    4           2           400         2           3
2                    3           2           300         2           3
3                    2           2           200         2           3
1                    1           3           42          3           1

答案 2 :(得分:0)

WITH q0 AS (SELECT qry.*, rank() AS r 
   FROM qry OVER (PARTITION BY race ORDER BY total_votes DESC))
SELECT q0.race, q0.candidate, q0.total_votes FROM q0 WHERE r<=q0.max_winners;