有时需要对查询对象中相同属性的行进行分组,然后查看分类后行的统计信息;
例如:财务报表中需要统计各个部门每年开销,那么就要已部门进行分类,然后在员工工资表中将同各部门的员工工资进行求和;
下面进行分类说明:
使用group by 子句对行进行分组
以products表为例,select * from products
1、查询同一个产品类型的商品个数
select pp.product_type_id,count(pp.product_id) from products pp
group by pp.product_type_id
2、使用多列进行分组
select * from purchases;
分别通过用户和用户购买产品ID进行分类
select pp.customer_id,pp.product_id from purchases pp
group by pp.customer_id,pp.product_id;
3、使用order by 子句对分组进行排序
如上2的sql,按照customer_id进行排序
select pp.customer_id,pp.product_id from purchases pp
group by pp.customer_id,pp.product_id
order by pp.customer_id;
使用聚合函数的错误用法:
(1)当查询语句中包含一个聚合函数时,而所选择的列并不在聚合函数中,那么这些列就必须在group by子句中,否则就会报错;
如:select pp.product_type_id,sum(pp.price) from products pp;
ORA-00937: not a single-group group function
(2)不能在where子句中使用聚合函数来限制行,如果这样就会包ORA-00934错误;
如:select pp.product_type_id,sum(pp.price) from products pp where sum(pp.price) > 100 group by pp.product_type_id;
ORA-00934: group function is not allowed here
4、使用having子句过滤进行分组
如上(2)情况,需要使用having子句进行分组条件过滤;
having子句的整体格式如下
select ...
from....
where ...
group ....
having...
order by ...
如上products表,根据产品类型进行分类,并计算每个分类中产品价格小于15元的记录的平均值,然后将平均值大于13的分组显示出来,并按照平均值的大小进行排序;
如:select pp.product_type_id, avg(pp.price)
from products pp
where pp.price < 50
group by pp.product_type_id
having avg(pp.price)>20
order by avg(pp.price);