一、group by

1、语法

group by ...
group by .... having ...
where ... group by ...
where ... group by ... having ...
where ... group by ... order by ...

2、示例

  • 查询目前班级名称(group by
    select distinct class from student
    select class from student GROUP BY class
    (注释:dixtinct 去重)

  • 查询目前每个班级的人数(group by
    select class,count(sname) from student GROUP BY class

  • 查找薪水记录超过15条的员工号emp_no以及其对应的记录次数t(group by … having
    select emp_no,count(emp_no) t from salaries group by emp_no having t>15 ;
    在这里插入图片描述

  • 查询出1975年以后出生 男神和女神的人数(where … group by
    select sex ,count(sname) from student where birthday >=‘1975-01-01’ GROUP BY sex

  • 查询哪一个课程分数良好(>=85)人数大于2的课程编号(where … group by …having
    select cno ,count(degree) from score where degree>=85 GROUP BY cno having count(degree)>=2

  • 查询出1975年以后出生 男神和女神的人数并按人数降序排序(where … group by … order by
    select sex ,count(sname) as s from student where birthday >=‘1975-01-01’ GROUP BY sex order by s desc

二、order by

1、语法

order by ... asc            ----升序
order by ... desc           ----降序

2、示例

select * from student order by age asc
select * from student order by age desc

--按工资薪酬降序排序
  select emp_no,salary from salaries
order by salary desc

在这里插入图片描述

三、rank

1.概念

1、RANK()
计算排序时,若存在相同位次,会跳过之后的位次。
例如,有3条排在第1位时,排序为:1,1,1,4······

2、DENSE_RANK()
这就是题目中所用到的函数,在计算排序时,若存在相同位次,不会跳过之后的位次。
例如,有3条排在第1位时,排序为:1,1,1,2······

3、ROW_NUMBER()
这个函数赋予唯一的连续位次。
例如,有3条排在第1位时,排序为:1,2,3,4······

2.示例

代码如下(示例):

select emp_no,salary,
       dense_rank() over (order by salary desc) as t_rank
from salaries
order by salary desc,emp_no asc

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐