为此,使用AVG()作为平均值,并使用GROUP BY对重复列(产品ID)的记录进行分组。让我们首先创建一个表-
create table DemoTable1490 -> ( -> ProductId varchar(20), -> ProductPrice int -> );
使用插入命令在表中插入一些记录-
insert into DemoTable1490 values('PRODUCT_100',700); insert into DemoTable1490 values('PRODUCT_200',500); insert into DemoTable1490 values('PRODUCT_200',1000); insert into DemoTable1490 values('PRODUCT_100',1300); insert into DemoTable1490 values('PRODUCT_200',300);
使用select语句显示表中的所有记录-
select * from DemoTable1490;
这将产生以下输出-
+-------------+--------------+ | ProductId | ProductPrice | +-------------+--------------+ | PRODUCT_100 | 700 | | PRODUCT_200 | 500 | | PRODUCT_200 | 1000 | | PRODUCT_100 | 1300 | | PRODUCT_200 | 300 | +-------------+--------------+ 5 rows in set (0.00 sec)
这是查找平均值的查询-
select ProductId,avg(ProductPrice) from DemoTable1490 -> group by ProductId;
这将产生以下输出-
+-------------+-------------------+ | ProductId | avg(ProductPrice) | +-------------+-------------------+ | PRODUCT_100 | 1000.0000 | | PRODUCT_200 | 600.0000 | +-------------+-------------------+ 2 rows in set (0.03 sec)