6 solutions to explain MySQL general query strategy
175. Combine two tables
select FirstName, LastName, City, State
from Person left join Address
on Person.PersonId = Address.PersonId;
176. Second highest salary
SELECT
IFNULL(
(SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1),
NULL) AS SecondHighestSalary
177. Nth highest salary
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
declare M int;
set M:=N-1;
RETURN (
# Write your MySQL query statement below.
select IFNULL(
(select distinct Salary from Employee order by Salary desc limit 1 offset M),
null
)
);
END
Pay attention to two points:
limit 1 offset M
Andlimit M, 1
equivalentdeclare M int; set M:=N-1;
Write inBEGIN
andRETURN
between
178. Score Ranking
A well-understood approach:
select
a.Score as score ,
(select count(distinct b.Score) from Scores b where b.Score >=a.Score) as `rank`
from Scores a order by Score DESC;
Open a new column, use the select count(distinct b.Score) from Scores b where b.Score >=a.Score
serial number
Window function approach:
select
score,
dense_rank() over (order by score desc) as `rank`
from Scores;
Window function:
- rank
- dense_rank
- row_number
Graphical SQL Interview Questions: Classic Ranking Questions