0

I've looking for answers but haven't found anything that I could apply to my table, or understand.

I've a table called Vote with 2 fields idVotant and idVote (idVotant is the guy who made the vote, and idVote is the guy for who he voted)

If I use this:

SELECT count(idVote) FROM Vote WHERE idVote=6

I get the number of votes that guy n°6 received.

If I use this:

SELECT idVote,count(idVote) AS votes FROM Vote GROUP BY idVote ORDER BY votes DESC

I get the list of all the guys and the number of votes they have.

Now, what I want to do is get the position of each guys, and of a specific one.
The guy n°6 is first because he got more votes, the guy n°2 is second.
And asking the position of a guy like which position is guy n°3 ?

4

3 回答 3

0

编辑:(这个地址平票)

 SELECT * FROM
  (SELECT idVote, Votes, CASE 
        WHEN @totalvotes = Votes THEN @rank 
        ELSE @rank := @rank + 1 
      END AS Ranking, @totalvotes := Votes  FROM
        (SELECT idVote, count(*) as Votes
         FROM Vote
         GROUP BY idVote ORDER BY Votes DESC) V
   JOIN (SELECT @rank:=0) r) VoteRanking

见我的SQLFiddle

如果你想选择特定的排名让我们说排名第二,只需添加:

 WHERE Ranking=2
于 2013-05-13T12:51:27.957 回答
0

尝试这个:

SELECT @rownum:=@rownum+1 AS position, u.idVote, u.votes
FROM (
    SELECT idVote, count(idVote) AS votes FROM Vote GROUP BY idVote ORDER BY votes DESC
) u,
(SELECT @rownum:=0) r

在此处查看演示。我基本上已经将您的 SQL 查询包装在rownum查询中

要查找特定的人,请使用以下命令:

SELECT * FROM (
  SELECT @rownum:=@rownum+1 AS position, u.idVote, u.votes
  FROM (
    SELECT idVote, count(idVote) AS votes FROM Vote GROUP BY idVote ORDER BY votes DESC
  ) u,
  (SELECT @rownum:=0) r
) ranked_vote WHERE idVote=6
于 2013-05-13T12:45:26.260 回答
0

尝试以下:

 SELECT idVote,count(idVote) AS votes,ROW_NUMBER() OVER (ORDER BY count(idVote) desc)  AS Rank
       FROM Vote 
       GROUP BY idVote
       ORDER BY count(idVote) 
       DESC

SQLFIDDLE

希望它有帮助。

于 2013-05-13T12:47:09.577 回答