MySQL SELECT产品的“每件产品平均价格” <值?

让我们首先创建一个表-

mysql> create table DemoTable848(
   ProductId int,
   ProductPrice int
);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable848 values(100,30);
mysql> insert into DemoTable848 values(101,50);
mysql> insert into DemoTable848 values(100,40);
mysql> insert into DemoTable848 values(101,25);
mysql> insert into DemoTable848 values(100,20);

使用select语句显示表中的所有记录-

mysql> select *from DemoTable848;

这将产生以下输出-

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

以下是查询,以选择“每个产品的平均价格” <值的产品。在这里,我们希望平均值小于35。这仅对ProductId为100的相应列值有效-

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

这将产生以下输出-

+-----------+-------------------+
| ProductId | avg(ProductPrice) |
+-----------+-------------------+
| 100       | 30.0000           |
+-----------+-------------------+
1 row in set (0.00 sec)