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

现有员工信息表如下:

M
Mars Liu 已提交
5
```mysql
M
Mars Liu 已提交
6 7 8 9 10 11 12 13 14 15 16 17 18
create table employee
(
    id     serial primary key,
    name   text,
    dept   text,
    salary money
);
```

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

## 答案

M
Mars Liu 已提交
19
```mysql
M
Mars Liu 已提交
20 21 22 23 24 25 26 27 28 29
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;
```

## 选项

### 结构错误

M
Mars Liu 已提交
30
```mysql
M
Mars Liu 已提交
31 32 33 34 35 36 37 38
select id, name, dept, max(salary) as salary
from employee
group by dept
having id < 6;
```

### 结构错误

M
Mars Liu 已提交
39
```mysql
M
Mars Liu 已提交
40 41 42 43 44 45 46 47 48 49 50
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;
```

### 结构错误

M
Mars Liu 已提交
51
```mysql
M
Mars Liu 已提交
52 53 54 55 56 57 58 59 60 61
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
```

### 结构错误

M
Mars Liu 已提交
62
```mysql
M
Mars Liu 已提交
63 64 65 66 67 68 69
select id, name, dept, salary, rank() over (partition by dept order by salary desc) as r
from employee
where r <= 5;
```

### 结构错误

M
Mars Liu 已提交
70
```mysql
M
Mars Liu 已提交
71 72 73 74
select id, name, dept, salary, rank() as r over (partition by dept order by salary desc)
from employee
where r <= 5;
```