salary.md 1.9 KB
Newer Older
M
Mars Liu 已提交
1 2 3 4
# 工资最高的人

现有员工信息表如下:

fix bug  
张志晨 已提交
5
```sql
M
Mars Liu 已提交
6 7 8 9 10 11 12 13 14 15 16
create table employee
(
    id     serial primary key,
    name   text,
    dept   text,
    salary money
);
```

下面哪条查询,可以给出每个部门工资最高的前五个员工的 id, name, dept, salary 四项信息?

M
Mars Liu 已提交
17 18
<hr/>

F
feilong 已提交
19
点击进入[MySQL实战练习环境](https://mydev.csdn.net/product/pod/new?image=cimg-centos7-skilltreemysql&connect=auto&create=auto&utm_source=skill){target="_blank"}。
F
feilong 已提交
20

F
feilong 已提交
21 22
* `show databases;` 列出所有数据库
* `show tables;` 列出所有表
M
Mars Liu 已提交
23

M
Mars Liu 已提交
24 25
## 答案

fix bug  
张志晨 已提交
26
```sql
M
Mars Liu 已提交
27
select id, name, dept, salary
28 29 30 31 32 33 34
from (select id, 
             name, 
             dept, 
             salary, 
             rank() over (
                 partition by dept 
                 order by salary desc) as r
M
Mars Liu 已提交
35 36 37 38 39 40 41 42
      from employee) as t
where r <= 5;
```

## 选项

### 结构错误

fix bug  
张志晨 已提交
43
```sql
M
Mars Liu 已提交
44 45 46 47 48 49 50 51
select id, name, dept, max(salary) as salary
from employee
group by dept
having id < 6;
```

### 结构错误

fix bug  
张志晨 已提交
52
```sql
M
Mars Liu 已提交
53 54 55 56 57 58 59 60 61 62 63
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;
```

### 结构错误

fix bug  
张志晨 已提交
64
```sql
M
Mars Liu 已提交
65 66
select l.id, l.name, l.dept, l.salary
from employee as l
67 68 69 70 71
         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
M
Mars Liu 已提交
72 73 74 75
```

### 结构错误

fix bug  
张志晨 已提交
76
```sql
77 78 79 80 81 82 83
select id, 
       name, 
       dept, 
       salary, 
       rank() over (
           partition by dept 
           order by salary desc) as r
M
Mars Liu 已提交
84 85 86 87 88 89
from employee
where r <= 5;
```

### 结构错误

fix bug  
张志晨 已提交
90
```sql
91 92 93 94 95 96 97
select id, 
       name, 
       dept, 
       salary, 
       rank() as r over (
            partition by dept 
            order by salary desc)
M
Mars Liu 已提交
98 99 100
from employee
where r <= 5;
```