1. 程式人生 > >Leetcode sql演算法題

Leetcode sql演算法題

主要參考四火的部落格:

http://www.raychase.net/2810

--175  Combine Two Tables
--左連線
select p.FirstName, p.LastName, a.City, a.State
  from Person p
  left outer join Address a
    on p.PersonId = a.PersonId;

--176 Second Highest Salary
--解法一 使用兩次max找到第二大的作為過濾條件
select MAX(Salary)
  from (SELECT Salary
          from Employee
         where Salary < (select MAX(Salary) from Employee ));
--解法二 mysql主要使用desc limit( m,n) 從m開始,的n個 初始下標是0
select IFNULL((select e.Salary
                from Employee e
               group by e.Salary
               order by e.Salary desc limit 1, 1),
              NULL) SecondHighestSalary;
              
--177	Nth Highest Salary
--取到第N大的 需要定義一個function了
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
DECLARE M INT;
SET M=N-1;
  RETURN (
      # Write your MySQL query statement below.
      SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT M, 1
  );
END