LeetCode | SQL | 5题

175. Combine Two Tables

6778119-ead1847207484947.png
image.png
Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:

FirstName, LastName, City, State

select a.FirstName, a.LastName, b.City, b.State
from Person a
left join Address b
on a.PersonId = b.PersonId

176. Second Highest Salary

6778119-02efd77b551ec7fa.png
image.png

select 
    (select distinct Salary 
    from Employee
    order by Salary DESC
    limit 1,1) as SecondHighestSalary;

177. Nth Highest Salary

6778119-e588038c3876c728.png
image

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  set N = N-1;    # 先令N=N-1,limit那里不能做运算
  RETURN (
      select distinct Salary 
       from Employee
       order by Salary desc
       limit N,1
  );
END

178. Rank Scores

6778119-ee5744b1b5b355b1.png
image.png
6778119-114cd338d11d2b88.png
image.png

select Score,
       (select count(*) from (select distinct Score s from Scores) tmp 
       where s >= Score) as Rank
from Scores
order by Score desc

180. Consecutive Numbers

6778119-fcf0e4a6e84b8982.png
image.png

select distinct l1.Num as ConsecutiveNums
from 
    Logs l1,
    Logs l2,
    Logs l3
where
    l1.id = l2.id - 1
    and l2.id = l3.id - 1
    and l1.Num = l2.Num
    and l2.Num = l3.Num
;

猜你喜欢

转载自blog.csdn.net/weixin_33743248/article/details/87093987
今日推荐