Count duplicate ids and display the result in a separate column with MySQL

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable1453
   -> (
   -> CustomerId int,
   -> CustomerReviewNumber int
   -> );
Query OK, 0 rows affected (0.58 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1453 values(10,4);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1453 values(10,4);
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable1453 values(11,5);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1453 values(11,5);
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable1453 values(11,5);
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable1453 values(13,2);
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable1453 values(11,5);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1453 values(10,4);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1453 values(13,2);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1453;

This will produce the following output −

+------------+----------------------+
| CustomerId | CustomerReviewNumber |
+------------+----------------------+
|         10 |                    4 |
|         10 |                    4 |
|         11 |                    5 |
|         11 |                    5 |
|         11 |                    5 |
|         13 |                    2 |
|         11 |                    5 |
|         10 |                    4 |
|         13 |                    2 |
+------------+----------------------+
9 rows in set (0.00 sec)

Following is the query to count duplicate ids −

mysql> select CustomerId,count(distinct CustomerReviewNumber)
   -> from DemoTable1453
   -> group by CustomerId;

This will produce the following output −

+------------+--------------------------------------+
| CustomerId | count(distinct CustomerReviewNumber) |
+------------+--------------------------------------+
|         10 |                                    1 |
|         11 |                                    1 |
|         13 |                                    1 |
+------------+--------------------------------------+
3 rows in set (0.14 sec)
raja
Published on 10-Dec-2019 10:34:23
Advertisements