博客
关于我
mysql中还有窗口函数?这是什么东西?
阅读量:791 次
发布时间:2023-02-11

本文共 2201 字,大约阅读时间需要 7 分钟。

图片

什么是窗口函数?

mysql8.0的版本中,新增了一个窗口函数,用他可以实现很多新的查询方式。窗口函数类似于sun()count()那样的集合函数,但它并不会将多行查询结果合并为一行,而是将结果放回多行中。什么意思呢?就是说窗口函数是不需要group by的。

窗口函数-排名

首先我们创建一个名字为test_2的数据表;

mysql> create table test_2 (name char(200) not null, brcount int(20) not null);Query OK, 0 rows affected, 1 warning (0.02 sec)mysql>

然后插入几条数据;

mysql> insert into test_2 values ('test1', 10), ('test2', 14), ('test3', 8), ('test4', 99), ('test5', 3);Query OK, 5 rows affected (0.01 sec)Records: 5  Duplicates: 0  Warnings: 0mysql>

查看下表中数据:

mysql> select * from test_2;+-------+---------+| name  | brcount |+-------+---------+| test1 |      10 || test2 |      14 || test3 |       8 || test4 |      99 || test5 |       3 |+-------+---------+5 rows in set (0.00 sec)mysql>

按照字段brcount从小到大来进行排序,可以利用窗口函数来实现;

mysql> select *, rank() over w1 as 'rand' from test_2 window w1 as (order by brcount);+-------+---------+------+| name  | brcount | rand |+-------+---------+------+| test5 |       3 |    1 || test3 |       8 |    2 || test1 |      10 |    3 || test2 |      14 |    4 || test4 |      99 |    5 |+-------+---------+------+5 rows in set (0.01 sec)mysql>

这里创建了名称为w1的窗口函数,规定对brcount字段进行排序,然后在select子句中对窗口函数w1执行rank()方法,将结果输出为rank字段。

RANK()函数为结果集的分区中的每一行分配一个排名。行的等级由一加上前面的等级数指定。

需要注意的是,在这里的windows w1是可选的,如下:

mysql> select *, rank() over w1 as 'rand' from test_2 window w1 as (order by brcount);+-------+---------+------+| name  | brcount | rand |+-------+---------+------+| test5 |       3 |    1 || test3 |       8 |    2 || test1 |      10 |    3 || test2 |      14 |    4 || test4 |      99 |    5 |+-------+---------+------+5 rows in set (0.00 sec)mysql>

亦或者查一下各自所占百分比;

mysql> select *, (brcount)/(sum(brcount) over()) as rate from test_2;+-------+---------+--------+| name  | brcount | rate   |+-------+---------+--------+| test1 |      10 | 0.0746 || test2 |      14 | 0.1045 || test3 |       8 | 0.0597 || test4 |      99 | 0.7388 || test5 |       3 | 0.0224 |+-------+---------+--------+5 rows in set (0.00 sec)mysql>

至此,本文结束。

更多内容请转至VX公众号 “运维家” ,获取最新文章。

------ “运维家” ------

------ “运维家” ------

------ “运维家” ------

临武县运维工程师培训,温州运维工程师,通达oa实施运维工程师,呼叫中心运维工程师面试

腾讯idc运 维工程师面试,运维工程师samba,运维工程师的行业是什么,
运维工程师的来历,运维工程师好找嘛,运维 工程师出入,运维工程师自学可行

转载地址:http://dtbfk.baihongyu.com/

你可能感兴趣的文章
mySQL 多个表求多个count
查看>>
mysql 多字段删除重复数据,保留最小id数据
查看>>
MySQL 多表联合查询:UNION 和 JOIN 分析
查看>>
MySQL 大数据量快速插入方法和语句优化
查看>>
mysql 如何给SQL添加索引
查看>>
mysql 字段区分大小写
查看>>
mysql 字段合并问题(group_concat)
查看>>
mysql 字段类型类型
查看>>
MySQL 字符串截取函数,字段截取,字符串截取
查看>>
MySQL 存储引擎
查看>>
mysql 存储过程 注入_mysql 视图 事务 存储过程 SQL注入
查看>>
MySQL 存储过程参数:in、out、inout
查看>>
mysql 存储过程每隔一段时间执行一次
查看>>
mysql 存在update不存在insert
查看>>
Mysql 学习总结(86)—— Mysql 的 JSON 数据类型正确使用姿势
查看>>
Mysql 学习总结(87)—— Mysql 执行计划(Explain)再总结
查看>>
Mysql 学习总结(88)—— Mysql 官方为什么不推荐用雪花 id 和 uuid 做 MySQL 主键
查看>>
Mysql 学习总结(89)—— Mysql 库表容量统计
查看>>
mysql 实现主从复制/主从同步
查看>>
mysql 审核_审核MySQL数据库上的登录
查看>>