简体   繁体   中英

MySQL: SELECT a Winner, returning their rank

Earlier I asked this question , which basically asked how to list 10 winners in a table with many winners, according to their points.

This was answered.

Now I'm looking to search for a given winner X in the table, and find out what position he is in, when the table is ordered by points.

For example, if this is the table:

     Winners:
NAME:____|__POINTS:
Winner1  |  1241
Winner2  |  1199
Sally    |  1000
Winner4  |  900
Winner5  |  889
Winner6  |  700
Winner7  |  667
Jacob    |  623
Winner9  |  622
Winner10 |  605
Winner11 |  600
Winner12 |  586
Thomas   |  455
Pamela   |  434
Winner15 |  411
Winner16 |  410

These are possible inputs and outputs for what I want to do:

Query:  "Sally", "Winner12", "Pamela", "Jacob"
Output: 3        12          14        623

How can I do this? Is it possible, using only a MySQL statement? Or do I need PHP as well?

This is the kind of thing I want:

WHEREIS FROM Winners WHERE Name='Sally' LIMIT 1

Ideas?

Edit - NOTE: You do not have to deal with the situation where two Winners have the same Points (assume for simplicity's sake that this does not happen).

I think this will get you the desired result. Note that i properly handles cases where the targeted winner is tied for points with another winner. (Both get the same postion).

SELECT COUNT(*) + 1 AS Position
FROM myTable
WHERE Points > (SELECT Points FROM myTable WHERE Winner = 'Sally')

Edit :
I'd like to "plug" Ignacio Vazquez-Abrams ' answer which, in several ways, is better than the above.
For example, it allows listing all (or several) winners and their current position.
Another advantage is that it allows expressing a more complicated condition to indicate that a given player is ahead of another (see below). Reading incrediman 's comment to the effect that there will not be "ties" prompted me to look into this; the query can be slightly modified as follow to handle the situation when players have same number of points (such players would formerly have been given the same Position value, now the position value is further tied to their relative Start values).

SELECT w1.name, (
  SELECT COUNT(*)
  FROM winners AS w2
  WHERE (w2.points > w1.points) 
     OR (W2.points = W1.points AND W2.Start < W1.Start)  -- Extra cond. to avoid ties.
)+1 AS rank
FROM winners AS w1
-- WHERE W1.name = 'Sally'   -- optional where clause
SELECT w1.name, (
  SELECT COUNT(*)
  FROM winners AS w2
  WHERE w2.points > w1.points
)+1 AS rank
FROM winners AS w1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM