xuthus / 数据库SQL实战SQLMIT

Explore and code with more than 6 million developers，Free private repositories ！：）
23.对所有员工的薪水按照salary进行按照1-N的排名.md 1.36 KB
xuthus authored 2019-08-03 23:19 . add:22-25

对所有员工的薪水按照salary进行按照1-N的排名

题目描述

```CREATE TABLE `salaries` (
`emp_no` int(11) NOT NULL,
`salary` int(11) NOT NULL,
`from_date` date NOT NULL,
`to_date` date NOT NULL,
PRIMARY KEY (`emp_no`,`from_date`));```

答案

`select t1.emp_no,t1.salary,count(distinct t2.salary) rank from (select * from salaries s where to_date = '9999-01-01') t1 , (select * from salaries s where to_date = '9999-01-01') t2 where t2.salary >= t1.salary group by t1.emp_no order by rank`

题解

1、获得两个临时表t1,t2

```(select * from salaries s where to_date = '9999-01-01') t1
(select * from salaries s where to_date = '9999-01-01') t2```

2、用第一个临时表的t1.salary去和t2.salary进行比较，从何可以获得所有t1.salary小于t2.salary的数据集，正是如此，我们可以对用户进行分组，统计每个用户对应的salary小于其他用户的数据条数，此为排名。为什么count时要去重，因为可能存在相同排名的人

`select t1.emp_no,count(distinct t2.salary) from t1,t2 where t2.salary >= t1.salary group by t1.emp_no`