Initial commit

This commit is contained in:
JIAL 2023-11-18 11:09:14 +08:00
commit 83092fc2df
2 changed files with 107 additions and 0 deletions

0
README.md Normal file
View File

107
VSCode/SQL笔记.sql Normal file
View File

@ -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窗口分析函数leadlag详解
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