MySQL query to find the top two highest scores

MySQLMySQLi Database

For this, use aggregate function MAX(). Let us first create a table −

mysql> create table DemoTable1383
   -> (
   -> Id int,
   -> PlayerScore int
   -> );
Query OK, 0 rows affected (0.90 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1383 values(200,78);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1383 values(200,89);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable1383 values(200,89);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1383 values(200,87);
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable1383 values(203,97);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1383 values(200,57);
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1383;

This will produce the following output −

+------+-------------+
| Id   | PlayerScore |
+------+-------------+
|  200 |          78 |
|  200 |          89 |
|  200 |          89 |
|  200 |          87 |
|  203 |          97 |
|  200 |          57 |
+------+-------------+
6 rows in set (0.00 sec)

Following is the query to find highest score and display distinct value −

mysql> select Id,max(PlayerScore) from DemoTable1383 group by Id order by max(PlayerScore) DESC;

This will produce the following output −

+------+------------------+
| Id   | max(PlayerScore) |
+------+------------------+
|  203 |               97 |
|  200 |               89 |
+------+------------------+
2 rows in set (0.00 sec)
raja
Published on 11-Nov-2019 10:07:52
Advertisements