Find average of corresponding records (Product Price) from duplicate product ids in MYSQL


For this, use AVG() for average and GROUP BY to group records of duplicate column (Product Id). Let us first create a table −

mysql> create table DemoTable1490
   -> (
   -> ProductId varchar(20),
   -> ProductPrice int
   -> );
Query OK, 0 rows affected (0.43 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1490 values('PRODUCT_100',700);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable1490 values('PRODUCT_200',500);
Query OK, 1 row affected (0.31 sec)
mysql> insert into DemoTable1490 values('PRODUCT_200',1000);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable1490 values('PRODUCT_100',1300);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable1490 values('PRODUCT_200',300);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1490;

This will produce the following output −

+-------------+--------------+
| ProductId   | ProductPrice |
+-------------+--------------+
| PRODUCT_100 |          700 |
| PRODUCT_200 |          500 |
| PRODUCT_200 |         1000 |
| PRODUCT_100 |         1300 |
| PRODUCT_200 |          300 |
+-------------+--------------+
5 rows in set (0.00 sec)

Here is the query to find average −

mysql> select ProductId,avg(ProductPrice) from DemoTable1490
   -> group by ProductId;

This will produce the following output −

+-------------+-------------------+
| ProductId   | avg(ProductPrice) |
+-------------+-------------------+
| PRODUCT_100 |         1000.0000 |
| PRODUCT_200 |          600.0000 |
+-------------+-------------------+
2 rows in set (0.03 sec)

Updated on: 11-Dec-2019

320 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements