LeetCode-SQL-569. 员工薪水中位数
程序员文章站
2022-06-11 14:29:40
...
sql架构
Create table If Not Exists Employee (Id int, Company varchar(255), Salary int)
Truncate table Employee
insert into Employee (Id, Company, Salary) values ('1', 'A', '2341')
insert into Employee (Id, Company, Salary) values ('2', 'A', '341')
insert into Employee (Id, Company, Salary) values ('3', 'A', '15')
insert into Employee (Id, Company, Salary) values ('4', 'A', '15314')
insert into Employee (Id, Company, Salary) values ('5', 'A', '451')
insert into Employee (Id, Company, Salary) values ('6', 'A', '513')
insert into Employee (Id, Company, Salary) values ('7', 'B', '15')
insert into Employee (Id, Company, Salary) values ('8', 'B', '13')
insert into Employee (Id, Company, Salary) values ('9', 'B', '1154')
insert into Employee (Id, Company, Salary) values ('10', 'B', '1345')
insert into Employee (Id, Company, Salary) values ('11', 'B', '1221')
insert into Employee (Id, Company, Salary) values ('12', 'B', '234')
insert into Employee (Id, Company, Salary) values ('13', 'C', '2345')
insert into Employee (Id, Company, Salary) values ('14', 'C', '2645')
insert into Employee (Id, Company, Salary) values ('15', 'C', '2645')
insert into Employee (Id, Company, Salary) values ('16', 'C', '2652')
insert into Employee (Id, Company, Salary) values ('17', 'C', '65')
SELECT
Employee.Id, Employee.Company, Employee.Salary
FROM
Employee,
Employee alias
WHERE
Employee.Company = alias.Company
GROUP BY Employee.Company , Employee.Salary
HAVING SUM(CASE
WHEN Employee.Salary = alias.Salary THEN 1
ELSE 0
END) >= ABS(SUM(SIGN(Employee.Salary - alias.Salary)))
ORDER BY Employee.Id
;
SELECT
Id, Company, Salary
FROM
(SELECT
e.Id,
e.Salary,
e.Company,
IF(@prev = e.Company, @Rank:aaa@qq.com + 1, @Rank:=1) AS rank,
@prev:=e.Company
FROM
Employee e, (SELECT @Rank:=0, @prev:=0) AS temp
ORDER BY e.Company , e.Salary , e.Id) Ranking
INNER JOIN
(SELECT
COUNT(*) AS totalcount, Company AS name
FROM
Employee e2
GROUP BY e2.Company) companycount ON companycount.name = Ranking.Company
WHERE
Rank = FLOOR((totalcount + 1) / 2)
OR Rank = FLOOR((totalcount + 2) / 2)
;
推荐阅读
-
数据库SQL实战题:获取员工其当前的薪水比其manager当前薪水还高的相关信息(教程)
-
数据库SQL实战:查找员工编号emp_now为10001其自入职以来的薪水salary涨幅值growth(教程)
-
数据库SQL实战之查找所有员工入职时候的薪水情况(题解)
-
数据库SQL实战:获取所有部门中当前员工薪水最高的相关信息(教程)
-
【MySQL牛客】12.获取所有部门中当前员工当前薪水最高的相关信息
-
以部门号分组,查询薪水前三的员工
-
【MySQL牛客】7.查找薪水变动超过15次的员工号emp_no以及其对应的变动次数t
-
数据库SQL实战:查找所有员工自入职以来的薪水涨幅情况(教程)
-
SQL实战.获取所有部门中当前员工薪水最高的相关信息
-
LeetCode-SQL-569. 员工薪水中位数