[LeetCode] 176. Second Highest Salary / 178. Rank Scores / 184. Department Highest Salary

bin·2023년 1월 16일
0

176. Second Highest Salary

https://leetcode.com/problems/second-highest-salary/description/

Requirements

Write an SQL query to report the second highest salary from the Employee table. If there is no second highest salary, the query should report null.
The query result format is in the following example.

💡 MAX()는 결과값이 없으면 NULL을 반환한다.

Solution

SELECT MAX(salary) AS SecondHighestSalary
FROM Employee
WHERE salary < (SELECT MAX(salary) FROM Employee) 

178. Rank Scores

https://leetcode.com/problems/rank-scores/

Requirements

Write an SQL query to rank the scores. The ranking should be calculated according to the following rules:
The scores should be ranked from the highest to the lowest.
If there is a tie between two scores, both should have the same ranking.
After a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no holes between ranks.
Return the result table ordered by score in descending order.
The query result format is in the following example.

💡 DENSE_RANK() : 동일한 값이면 중복 순위를 부여하고, 다음 순위는 중복 순위와 상관없이 순차적으로 반환한다.

Solution

SELECT score, DENSE_RANK() OVER (ORDER BY score DESC) rank
FROM Scores
ORDER BY rank ASC

184. Department Highest Salary

https://leetcode.com/problems/department-highest-salary/

Requirements

Write an SQL query to find employees who have the highest salary in each of the departments.
Return the result table in any order.
The query result format is in the following example.

💡 IN : 하나라도 일치한 데이터가 있다면 TRUE (= 비교만 가능)

Solution

SELECT d.name AS Department, e.name AS Employee, e.salary AS Salary 
FROM Employee e

INNER JOIN Department d
ON e.departmentId = d.id

WHERE (e.salary, e.departmentId) IN (SELECT MAX(salary), departmentId FROM Employee GROUP BY departmentId) 

0개의 댓글