Initial commit
This commit is contained in:
commit
83092fc2df
|
@ -0,0 +1,107 @@
|
|||
mysql自动排序函数dense_rank() over()、rank() over()、row_num() over()用法和区别
|
||||
区别:
|
||||
rank():是并列排序,会跳过重复序号
|
||||
dense_rank():是并列排序,不会跳过重复序号
|
||||
row_number():是顺序排序,不跳过任何一个序号,就是行号
|
||||
|
||||
|
||||
create table students(
|
||||
id int(11) auto_increment primary key,
|
||||
name varchar(50) not null,
|
||||
score int(4) not null
|
||||
);
|
||||
|
||||
insert into students(name,score) values
|
||||
('zhangsan', 100),
|
||||
('lisi', 99),
|
||||
('wangwu', 100),
|
||||
('trx', 90),
|
||||
('pjf', 99),
|
||||
('wzm', 96);
|
||||
|
||||
|
||||
mysql> select * from students;
|
||||
+----+----------+-------+
|
||||
| id | name | score |
|
||||
+----+----------+-------+
|
||||
| 1 | zhangsan | 100 |
|
||||
| 2 | lisi | 99 |
|
||||
| 3 | wangwu | 100 |
|
||||
| 4 | trx | 90 |
|
||||
| 5 | pjf | 99 |
|
||||
| 6 | wzm | 96 |
|
||||
+----+----------+-------+
|
||||
|
||||
使用三种不同的方法进行排序:
|
||||
select
|
||||
id,
|
||||
name,
|
||||
rank() over(order by score desc) `rank`,
|
||||
row_number() over(order by score desc) `row_number`,
|
||||
dense_rank() over(order by score desc) `dense_rank`
|
||||
from students;
|
||||
|
||||
--------------------------------- 结果 ------------------------------------
|
||||
+----+----------+-------+------+------------+------------+
|
||||
| id | name | score | rank | row_number | dense_rank |
|
||||
+----+----------+-------+------+------------+------------+
|
||||
| 1 | zhangsan | 100 | 1 | 1 | 1 |
|
||||
| 3 | wangwu | 100 | 1 | 2 | 1 |
|
||||
| 2 | lisi | 99 | 3 | 3 | 2 |
|
||||
| 5 | pjf | 99 | 3 | 4 | 2 |
|
||||
| 6 | wzm | 96 | 5 | 5 | 3 |
|
||||
| 4 | trx | 90 | 6 | 6 | 4 |
|
||||
+----+----------+-------+------+------------+------------+
|
||||
|
||||
|
||||
Sql窗口分析函数【lead、lag详解】
|
||||
表:Logs
|
||||
|
||||
+-------------+---------+
|
||||
| Column Name | Type |
|
||||
+-------------+---------+
|
||||
| id | int |
|
||||
| num | varchar |
|
||||
+-------------+---------+
|
||||
在 SQL 中,id 是该表的主键。
|
||||
id 是一个自增列。
|
||||
找出所有至少连续出现三次的数字。
|
||||
|
||||
返回的结果表中的数据可以按 任意顺序 排列。
|
||||
|
||||
结果格式如下面的例子所示:
|
||||
示例 1:
|
||||
输入:
|
||||
Logs 表:
|
||||
+----+-----+
|
||||
| id | num |
|
||||
+----+-----+
|
||||
| 1 | 1 |
|
||||
| 2 | 1 |
|
||||
| 3 | 1 |
|
||||
| 4 | 2 |
|
||||
| 5 | 1 |
|
||||
| 6 | 2 |
|
||||
| 7 | 2 |
|
||||
+----+-----+
|
||||
输出:
|
||||
Result 表:
|
||||
+-----------------+
|
||||
| ConsecutiveNums |
|
||||
+-----------------+
|
||||
| 1 |
|
||||
+-----------------+
|
||||
答案:
|
||||
select
|
||||
distinct p.num as ConsecutiveNums
|
||||
from(
|
||||
select
|
||||
id,
|
||||
num,
|
||||
lag(num,1)over(order by id) num1,
|
||||
lag(num,2)over(order by id) num2
|
||||
from
|
||||
Logs
|
||||
) p
|
||||
where
|
||||
p.num = p.num1 and p.num1 = p.num2
|
Loading…
Reference in New Issue