1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > sql语句中分组和排序(group by order by rank)

sql语句中分组和排序(group by order by rank)

时间:2018-07-05 10:37:57

相关推荐

sql语句中分组和排序(group by order by rank)

文章目录

一、group by1、语法2、示例二、order by1、语法2、示例三、rank1.概念2.示例

一、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 salariesorder 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_rankfrom salariesorder by salary desc,emp_no asc

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。