From 46adbcbfa82f51d25f690c7d0965fc892f83c881 Mon Sep 17 00:00:00 2001 From: Mars Liu Date: Thu, 2 Dec 2021 15:19:01 +0800 Subject: [PATCH] add window function --- .pre-commit-config.yaml | 2 +- .../2.Window Function/salary.md" | 67 +++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 "data/3.PostgreSQL\351\253\230\351\230\266/3.SQL\351\253\230\347\272\247\346\212\200\345\267\247/2.Window Function/salary.md" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index bb1c157..427f3af 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,6 @@ repos: - repo: git@codechina.csdn.net:csdn/skill_tree_hook.git - rev: 15a330214a4d7c2e0c0e42b5dfc3121a56f4dc23 + rev: 9430721405a57a809c0d93170fe307a89d979a4b hooks: - id: pre-commit verbose: true \ No newline at end of file diff --git "a/data/3.PostgreSQL\351\253\230\351\230\266/3.SQL\351\253\230\347\272\247\346\212\200\345\267\247/2.Window Function/salary.md" "b/data/3.PostgreSQL\351\253\230\351\230\266/3.SQL\351\253\230\347\272\247\346\212\200\345\267\247/2.Window Function/salary.md" new file mode 100644 index 0000000..8b5f5da --- /dev/null +++ "b/data/3.PostgreSQL\351\253\230\351\230\266/3.SQL\351\253\230\347\272\247\346\212\200\345\267\247/2.Window Function/salary.md" @@ -0,0 +1,67 @@ +# 工资最高的人 + +现有员工信息表如下: + +```postgresql +create table employee +( + id serial primary key, + name text, + dept text, + salary money +); +``` + +下面哪条查询,可以给出每个部门工资最高的前五个员工的 id, name, dept, salary 四项信息? + +## 答案 + +```postgresql +select id, name, dept, salary +from (select id, name, dept, salary, rank() over (partition by dept order by salary desc) as r + from employee) as t +where r <= 5; +``` + +## 选项 + +### 结构错误 + +```postgresql +select id, name, dept, max(salary) as salary +from employee +group by dept +having id < 6; +``` + +### 结构错误 + +```postgresql +select l.id, l.name, l.dept, l.salary +from employee as l + join (select max(salary) as salary, dept + from employee + group by dept) as r + on l.dept = r.dept and l.salary = r.salary +where count(r.id) <= 5; +``` + +### 结构错误 + +```postgresql +select l.id, l.name, l.dept, l.salary +from employee as l + join (select max(salary, 5) as salary, dept + from employee + group by dept) as r + on l.dept = r.dept and l.salary = r.salary +``` + +### 结构错误 + +```postgresql +select id, name, dept, salary, rank() over (partition by dept order by salary desc) as r +from employee +where r <= 5; +``` + -- GitLab