Using GROUP BY and COUNT in a single MySQL query to group duplicate records and display corresponding max value

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
   -> (
   -> ClientId int,
   -> Value int
   -> );
Query OK, 0 rows affected (0.79 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values(10,678);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(20,678);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(30,678);
Query OK, 1 row affected (0.09 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------+-------+
| ClientId | Value |
+----------+-------+
|       10 |   678 |
|       20 |   678 |
|       30 |   678 |
+----------+-------+
3 rows in set (0.00 sec)

Here is the query to GROUP does not work if COUNT is used −

mysql> select count(tbl.ClientId),max(tbl.ClientId) from DemoTable tbl
   -> group by Value;

This will produce the following output −

+---------------------+-------------------+
| count(tbl.ClientId) | max(tbl.ClientId) |
+---------------------+-------------------+
|                   3 |                30 |
+---------------------+-------------------+
1 row in set (0.00 sec)
raja
Published on 12-Dec-2019 09:52:55
Advertisements