如图所示
看似挺简单的SQL题目,但是我不知道怎么写这语句,请高手们多多解答,谢谢。
就是要用前两张表做出第三张表,我大致的思路是用join,然后group by,但做不出~~~
1
bosshida 2015-05-26 18:35:28 +08:00
|
2
wmttom 2015-05-26 19:57:36 +08:00 1
leetcode database #185 应该是这道题,database 题目里唯一一个hard难度的,属于 聚合 topN 类的问题,MySQL 不是非常好实现
https://leetcode.com/problems/department-top-three-salaries/ 我原来做的答案,写的比较乱,期待更高效的答案 SELECT c.Name AS Department,b.Name AS Employee, b.Salary AS Salary FROM ( SELECT *,@rn := if(@did = DepartmentId, if(@ss=Salary,@rn,@rn + 1) , 1) AS rn,@did := DepartmentId,@ss:=Salary FROM Employee,(SELECT @did:='',@rn:=0,@ss:=null) AS vars ORDER BY DepartmentId,Salary DESC ) AS b INNER JOIN Department AS c ON b.DepartmentId=c.Id WHERE b.rn<=3 ORDER BY b.DepartmentId,b.Salary DESC |
3
jianghu52 2015-05-26 21:07:10 +08:00
这个没那么复杂吧。我用union就搞定了啊。可能效率不是太好吧。
(SELECT name,salary, (case departid when 1 then 'IT' WHEN 2 then 'salers' else 'IT' END)as depart from employee where departid = 1 ORDER BY salary desc LIMIT 3) UNION (SELECT name,salary, (case departid when 1 then 'IT' WHEN 2 then 'salers' else 'IT' END)as depart from employee where departid = 2 ORDER BY salary DESC LIMIT 3) 我直接就没用第二张表,比较无赖。 |
4
wmttom 2015-05-27 01:34:32 +08:00 via iPhone
@jianghu52 这类题目的测试用例经常会有多个一样的值,top three 不一定是3个,可能有并列排名。
|
5
20150517 2015-05-27 02:43:38 +08:00
select * from (
select *, d,Name, rank(salary) OVER (PARTITION BY e.departmentid) rank from employee e inner join department d on d.id=e.departmentid) x where r<=3 其实很简单,关键是个rank函数 http://www.postgresql.org/docs/9.1/static/tutorial-window.html |
6
20150517 2015-05-27 02:44:52 +08:00
上面随便draft的,有些错误,应该是按salary倒顺序,看懂就ok
|
7
mhycy 2015-05-27 09:41:09 +08:00
SELECT
Department, Name, Salary FROM ( SELECT DepartmentId, Department.Name AS Department, employee.Name, Salary FROM Employee JOIN Department ON Department.Id = Employee.DepartmentId ) AS tmp WHERE Salary IN ( SELECT Salary FROM Employee WHERE DepartmentId = tmp.DepartmentId GROUP BY Salary ORDER BY Salary DESC LIMIT 0,3 ) ORDER BY DepartmentId ASC, Salary DESC 如果mysql子查询能用limit应该可以这么写 |
8
fangjinmin 2015-05-27 09:56:32 +08:00
我这个已经执行过,可以保证是正确的。
select department.name, employee.name, salary from employee, department where employee.departmentid = department.id and (select count(*) from employee as s where s.departmentid = employee.departmentid and s.salary >= employee.salary ) <=3 order by employee.departmentid, employee.salary desc; |
9
mhycy 2015-05-27 10:01:12 +08:00
|
10
jiaqidianbo OP |
11
wmttom 2015-05-28 18:13:54 +08:00
@jiaqidianbo @ 表示用户变量, 在 select 中赋值用 := ,MySQL 没有 rank,相当于自己模拟一个,http://stackoverflow.com/questions/3333665/rank-function-in-mysql
|