聚集函數以及如何利用聚集函數匯總數據
聚集函數運行在行組上,返回單個函數值
AVG()函數:?? 只能確定特定數列之的平均值,并且會忽略NULL值
select avg(prod_price) as avg_price from products;
select prod_price,prod_name,prod_id from products;
select sum(prod_price) as sum_price from products;
select prod_price,prod_name,prod_id from products where vend_id =1003;
select avg(prod_price) as avg_price from products where vend_id =1003;
select sum(prod_price) as sum_price from products where vend_id =1003;
當使用聚集函數時,不能進行篩選操作,會報錯。因為聚集函數返回的時單個的函數值,而篩選操作返回的時一系列行
COUNT()函數:? 計數函數
select count(*) as num_cust from customers;
select cust_name from customers;
select count(cust_email) as num_cust from customers;
select cust_email from customers;
這里對cust_email進行計數,count()函數會忽略null值,如果是count(*)則不會忽略NULL值
MAX()函數:?? 返回指定列最大值? 忽略NULL值
MIN()函數:功能同上
select max(prod_price) as max_price from products;
select prod_price from products;
sum()函數:? 求和
select sum(quantity) as items_ordered from orderitems where order_num = 20005;
select quantity from orderitems where order_num = 20005;
select item_price,quantity from orderitems where order_num = 20005;
select sum(quantity*item_price) as total_money from orderitems where order_num = 20005;
聚集不同值
select avg(distinct prod_price) as avg_price from products where vend_id = 1003;
指定供貨商1003,只考慮不同價格distinct prod_price