简体   繁体   中英

SQL ORDER BY logical double filtering possible?

I'm trying to figure out if there's a way to execute a query to order things by a certain row's numeric value, however under set conditions it will "double filter"(Probably incorrect term) the results and re-arrange them.

A good example of this is as follows:

A game has a scoreboard/leaderboard system in which it shows top ranked players, however when multiple players have the same skill-level, it will rank them by their amount of wins.

So, for example I have the following information in my database:

+----+--------+------+--------+
| id | player | wins | rating |
+----+--------+------+--------+
|  1 | Tom    |   12 |   1300 |
|  2 | Bob    |   18 |   1300 |
|  3 | Jim    |    7 |   1284 |
|  4 | Ed     |    2 |   1312 |
+----+--------+------+--------+

A standard order by 'rating' query will show them in this order

+----+--------+------+--------+
| id | player | wins | rating |
+----+--------+------+--------+
|  4 | Ed     |    2 |   1312 |
|  1 | Tom    |   12 |   1300 |
|  2 | Bob    |   18 |   1300 |
|  3 | Jim    |    7 |   1284 |
+----+--------+------+--------+

However, since Tom and Bob have the same rating, I want to order them by wins, so the table would look like this:

+----+--------+------+--------+
| id | player | wins | rating |
+----+--------+------+--------+
|  4 | Ed     |    2 |   1312 |
|  2 | Bob    |   18 |   1300 |
|  1 | Tom    |   12 |   1300 |
|  3 | Jim    |    7 |   1284 |
+----+--------+------+--------+

Any ideas? I know I can do this by running a single query, then creating a 2D array for everyone that has the same rating, then run a query for each rating (Where rating = ?) but that seems highly redundant.

In SQL you can have multiple ORDER BY clauses, separated by , s. The ordering is performed separately, first one being the leftmost one, and then the groups of records with the same value in the first sorting column are then sorted by the next statement, and so on. In your case the query would look like:

 SELECT * FROM players ORDER BY rating DESC, wins DESC;

You need to specify direction for ORDER BY. Check this :

SELECT id, player, wins, rating
FROM (values   
  (1, 'Tom', 12,  1300), 
  (2, 'Bob', 18,  1300), 
  (3, 'Jim', 7,   1284),
  (4, 'Ed',  2,   1312) 
 ) as T  (id, player, wins, rating)
ORDER BY rating desc, wins desc

Read SQL Server Book Online

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