一个客户订单Orders 表:
将每个客户订单分开,按照Customer分组,相同客户订单加在一起,
select customer ,SUM(OrderPrice) as totalPrice from Orders Group by Customer
如果要求平均值,必须要考虑相同客户有多个订单,
如:Customer='Bush'的客户有两个订单,
计算平均值时,要将这两个订单计算在一个人身上,
所以要先分组
select AVG(B.totalPrice) as avgPrice from
(select customer ,SUM(OrderPrice) as totalPrice from Orders Group by Customer) as B;
结果:4525.00= 18100/4
如果不分组的话:select AVG(OrderPrice) from Orders
结果:3016.6667=18100/6,此处多计算两个人
-- 查询订单在平均值以上的客户
select * from Orders where OrderPrice >(
select AVG(B.totalPrice) as avgPrice from
(select customer ,SUM(OrderPrice) as totalPrice from Orders Group by Customer) as B
) ;
结果只有一个客户的订单>平均值:
上面的求平均值还不完善,如果将序号为1的客户‘Bush’的OrderPrice改为2000,
每个客户的订单和:
它的平均值:4750,由上图可知大于4750的有Adams和Bush
仍使用上面的求大于平均值的客户:
从结果上可以看到少了Bush
COUNT() 函数返回匹配指定条件的行数。
1、COUNT(column_name) 函数返回指定列的值的数目(NULL 不计入):
select count(column_name) from orders;
SELECT COUNT( Customer) AS CustomerNilsen FROM Orders where Customer='Bush';
结果:2
=======================================================
SELECT COUNT( Customer) AS CustomerNilsen FROM Orders where Customer='Adams';
结果:1
=======================================================
2、SQL COUNT(DISTINCT column_name) 语法
COUNT(DISTINCT column_name) 函数返回指定列的不同值的数目:
SELECT COUNT(DISTINCT column_name) FROM table_name
注释:COUNT(DISTINCT) 适用于 ORACLE 和 Microsoft SQL Server,但是无法用于 Microsoft Access。
结果为不重复客户的数目:
SELECT COUNT(DISTINCT Customer) AS CustomerNilsen FROM Orders==》4
3、SQL COUNT(*) 实例
如果我们省略 WHERE 子句,比如这样计算所有数据
SELECT COUNT( * ) AS CustomerNumber FROM Orders ;==》6
HAVING 子句
在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与合计函数一起使用。