Summary of SQL issues

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;

Insert picture description here

176. Second highest salary

SELECT
    IFNULL(
      (SELECT DISTINCT Salary
       FROM Employee
       ORDER BY Salary DESC
        LIMIT 1 OFFSET 1),
    NULL) AS SecondHighestSalary

Insert picture description here

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:

  1. limit 1 offset MAnd limit M, 1equivalent
  2. declare M int; set M:=N-1;Write in BEGINand RETURNbetween

Insert picture description here

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.Scoreserial 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

Insert picture description here

Guess you like

Origin blog.csdn.net/TQCAI666/article/details/114410336