更新时间:2023年11月10日11时15分 来源:传智教育 浏览次数:
之前我们做的查询都是横向查询,它们都是根据条件一行一行的进行判断,而使用聚合函数查询是纵向查询,它是对一列的值进行计算,然后返回一个单一的值;另外聚合函数会忽略空值。
-- 1 查询商品的总条数 select count(*) from product; -- 2 查询价格大于200商品的总条数 select count(*) from product where price > 200; -- 3 查询分类为'c001'的所有商品的总和 select sum(price) from product where category_id = 'c001'; -- 4 查询商品的最大价格 select max(price) from product; -- 5 查询商品的最小价格 select min(price) from product; -- 6 查询分类为'c002'所有商品的平均价格 select avg(price) from product where category_id = 'c002';
聚合查询操作的示例代码如下:
-- 1 查询商品的总条数 select count(*) from product; -- 2 查询价格大于200商品的总条数 select count(*) from product where price > 200; -- 3 查询分类为'c001'的所有商品的总和 select sum(price) from product where category_id = 'c001'; -- 4 查询商品的最大价格 select max(price) from product; -- 5 查询商品的最小价格 select min(price) from product; -- 6 查询分类为'c002'所有商品的平均价格 select avg(price) from product where category_id = 'c002';
NULL值的处理
count函数对null值的处理,如果count函数的参数为星号(*),则统计所有记录的个数。而如果参数为某字段,不统计含null值的记录个数。
sum和avg函数对null值的处理,这两个函数忽略null值的存在,就好象该条记录不存在一样。
max和min函数对null值的处理,max和min两个函数同样忽略null值的存在。
NULL值的处理操作,示例代码如下:
-- 创建表
create table test_null(
c1 varchar(20),
c2 int
);
-- 插入数据
insert into test_null values('aaa',3);
insert into test_null values('bbb',3);
insert into test_null values('ccc',null);
insert into test_null values('ddd',6);
-- 测试
select count(*), count(1), count(c2) from test_null;
select sum(c2),max(c2),min(c2),avg(c2) from test_null;