MySQL SELECT products WHERE 'average price per product' < value?

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable848(
   ProductId int,
   ProductPrice int
);
Query OK, 0 rows affected (1.20 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable848 values(100,30);
Query OK, 1 row affected (0.57 sec)
mysql> insert into DemoTable848 values(101,50);
Query OK, 1 row affected (1.06 sec)
mysql> insert into DemoTable848 values(100,40);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable848 values(101,25);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable848 values(100,20);
Query OK, 1 row affected (0.31 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable848;

This will produce the following output −

+-----------+--------------+
| ProductId | ProductPrice |
+-----------+--------------+
| 100       | 30           |
| 101       | 50           |
| 100       | 40           |
| 101       | 25           |
| 100       | 20           |
+-----------+--------------+
5 rows in set (0.00 sec)

Following is the query to select products WHERE 'average price per product' < value. Here, we wanted the average to be less than 35. The same is only valid for corresponding column values with ProductId 100 −

mysql> select ProductId,avg(ProductPrice) from DemoTable848 group by ProductId having AVG(ProductPrice) < 35;

This will produce the following output −

+-----------+-------------------+
| ProductId | avg(ProductPrice) |
+-----------+-------------------+
| 100       | 30.0000           |
+-----------+-------------------+
1 row in set (0.00 sec)
raja
Published on 03-Sep-2019 11:55:34
Advertisements