题13:
根据下表,在不使用任何内置的SQL函数的情况下编写SQL查询来查找每个公司的薪水中位数。
解题思路:题目要求是不使用任何内置的SQL函数,因此使用HAVING的妙用。
(1)先做自连接,之后根据ID分组;
(2)生成两个子集:SUM(CASE WHEN a.Salary <= b.Salary THEN 1 ELSE 0 END) >= COUNT()/2 用来统计上半部分+1个;SUM(CASE WHEN a.Salary >= b.Salary THEN 1 ELSE 0 END) >= COUNT()/2 用来统计下半部分+1个
(3)用HAVING来求出(2)中两个的交集。
SELECT a.Id
FROM Employee aJOIN Employee bON a.Company = b.Company
GROUP BY a.Id
HAVING SUM(CASE WHEN a.Salary >= b.Salary THEN 1 ELSE 0 END)>=COUNT(*)/2 AND SUM(CASE WHEN a.Salary <= b.Salary THEN 1 ELSE 0 END) >= COUNT(*)/2
(4)最后把选出来的id放到WHERE里面从Employee表找出对应的行就可以了
SELECT *
FROM Employee
WHERE Id in (SELECT a.IdFROM Employee aJOIN Employee bON a.Company = b.CompanyGROUP BY a.IdHAVING SUM(CASE WHEN a.Salary >= b.Salary THEN 1 ELSE 0 END) >= COUNT(*)/2 AND SUM(CASE WHEN a.Salary <= b.Salary THEN 1 ELSE 0 END) >= COUNT(*)/2)
GROUP BY Company, Salary
ORDER BY Company;
注:
- WHEN a.Salary >= b.Salary:为判断条件;
- THEN 1 ELSE 0 END:当以上判断条件成立,则为1;
- sum:具有累加效果;
- count中无法使用条件语句,所以,此处使用sum而不用count