您当前的位置: 首页 >  sql

网易测试开发猿

暂无认证

  • 2浏览

    0关注

    221博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

MySQL数据排序与分组(详解)

网易测试开发猿 发布时间:2021-11-16 19:51:48 ,浏览量:2

MySQL数据排序与分组

一、数据排序:order by 用法:select 字段列表 from 表名 [where…] order by 字段名; order by 默认按字段数据的升序排列

降序:desc (放在字段名之后) 升序:asc

如:

select * from xxb1 order by 学号;
select * from xxb1 where 学号>=2 order by 学号 desc;

1、order by 放在select最后 2、order by可用别名 如:

select no 学号, name 姓名 from stu where age>20 order by 学号;

3、order by 复合排序 如:

select * from stu order by age,on;
Select * from stu order by age,on desc;    

注意:desc要紧跟前面字段名

例1 查询年龄一条最大、最小数据: 年龄最大:

select * from stu order by age limit 1;

年龄最小:

select * from stu order by age desc limit 1;

例2 查询1号、31号、15号出生的人员信息并按此(几号)降序排序

select 出生日期,right(出生日期,2) as 号数 from xxb1 where right(出生日期,2) in(‘01’,’15’,’31’) order by right(出生日期,2) desc;

二、分组:group by 只要select存在聚合函数、同时存在字段(多值数据)一定要在from之后加分组group by字段。除了聚合函数之外的函数/字段名都要放在group by之后。聚合函数不能放在where中。

用法:select 分组项1[,分组项2],分组表达式 from 表where 筛选条件group by 分组项1[,分组项2] having过滤分组; 如:

select count(*),left(name,1) from xxb1 group by left(name,1);
select avg(id),name from c1 group by id;

三、having(相当于where)放在group by之后 作用:作为聚合函数的用法 如:having count(*)>1;

select province, sex,count(cname) from users group by province, sex	having count(cname)>3;

请添加图片描述

关注
打赏
1665054478
查看更多评论
立即登录/注册

微信扫码登录

0.0371s