Score
0
Watch 44 Star 256 Fork 69

xuthus / 数据库SQL实战SQLMIT

Create your Gitee Account
Explore and code with more than 6 million developers,Free private repositories !:)
Sign up
Clone or download
23.对所有员工的薪水按照salary进行按照1-N的排名.md 1.36 KB
Copy Edit Web IDE Raw Blame History
xuthus authored 2019-08-03 23:19 . add:22-25

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

题目描述

对所有员工的当前(to_date='9999-01-01')薪水按照salary进行按照1-N的排名,相同salary并列且按照emp_no升序排列

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

题解

本题无法过MySQL的查询,但是测试通过了sqlite,也就是牛客网提交通过。

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

Comment ( 0 )

Sign in for post a comment