概念:
所谓组查询即将数据按照某列或者某些列相同的值进行分组,然后对该数组进行组函数运用,针对每一个组返回一个结果。
note:
1.组函数可以出现的位置:select子句和having子句
2.使用group by 将行划分成若干小组
3.having子句用来限制组结果返回。
语法:
select 。。。
from 。。。
where 。。。
group by col_name,col_name
having 。。。
order by 。。。
col_name:即将数据按照colName相同的值进行分组。
组函数常见的五个: distinct取消重复行
avg:求平均值 AVG(DISTINCT | ALL | N)
count:求总数 COUNT(DISTINCT | ALL | expr | *)
max:最大值 MAX(DISTINCT | ALL |expr)
min:最小值 MIN(DISTINCT | ALL | expr)
stddev: 求标准方差 STDDEV(DISTINCT | ALL | n)
sum: 求和 SUM(DISTINCT | ALL | n)
variance: 方差 VARIANCE(DISTINCT | ALL | n)
例:
select AVG(salary),MAX(salary),min(salary),sum (salary)
FROM s_emp
WHERE UPPER(title ) like “SALES%”;
select min(last_name),max(last_name) from s_emp;
avg([distinct] column) / sum ([distinct] column):可以作用在存储数字的列上。
对字符型数据的最大值,是按照首字母有A~Z的顺序排列,越往后,其值越大。当然,对于汉字则是按照其全拼音排列的,若是首字符相同,则比较下一个字符,依次类推。
max(),min():可以作用在任意类型的数据上。
count([distinct] column | *):
count( * ) :统计表中所有行数
count(column):返回所有非空的行数
条件:部门平均工资
部门平均工资大于1000
select dept_id, avg(salary) from S_emp group by dept_id having avg(salary) >1000;
1查找不以vp开头的所有员工
select last_name, first_name from S_emp where title not like ‘VP%’;
2并且将他们以职称分组
group by title
3,求各个职工的工资总和
sum(salary)
4将工资总和大于五千的职称和工资显示出来
having sum(salary)>5000;
总和:select title ,sum(salary) from s_emp where title not like ‘vp%’ group by title having sum(salary)>5000;
5.查看公司经理的id,并且显示该经理领导下的领取工资最低的员工的工资,不包含那些最低工资低于1000的员工的工资及其经理id,并按工资进行排序
select manger_id ,min(salary) from s_emp
where manger_id is not null
group by manger_id
having min(salary) >1000;
select customer_id ,count(id),sum(total)
from S_ord
group by customer_id;
连接查询
select customer_id ,name,count(S_ord.id),sum(total)
from S_ord ,S_customer
where S_ord.custom_id = S_customer.id
group by customer_id ,name;