175. Combine Two Tables
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
Note: FirstName, LastName, City, State来自不同的table, 所以用join, 要求必须显示人名,所以用left join(left join = left outer join)
# Write your MySQL query statement below
SELECT FirstName, LastName, City, State FROM Person LEFT JOIN Address
ON Person.PersonId = Address.PersonId
176 Second Highest Salary
解法1: using MAX(only used in this problem)
# Write your MySQL query statement below
select MAX(Salary) as SecondHighestSalary from Employee
where Salary < (select MAX(Salary) from Employee)
解法2: using limit & offset
# Write your MySQL query statement below
select (select distinct Salary from Employee order by Salary DESC limit 1 offset 1)
as SecondHighestSalary
Note: if we only write (select distinct Salary from Employee order by Salary DESC limit 1 offset 1) and there is no second highest salary, then the query should return “ ” instead of null
解法3:distinct count (can be used in Nth highest)
select (select MAX(Salary) from Employee as e
where 2 = (select count(distinct Salary) from Employee as p where e.Salary <= p.Salary))
AS SecondHighestSalary
Note: using MAX(Salary) to avoid multiple value return from subquery
177. Nth Highest Salary
解法1:distinct count
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
# Write your MySQL query statement below.
select (select Max(Salary) from Employee as e
where N = (select count(distinct Salary) from Employee as p where e.Salary <= p.Salary))
);
END
解法2:limit
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
Append:
Using MySQL LIMIT to Constrain The Number of Rows Returned By SELECT Statement
Introduction to MySQL LIMIT clause
The LIMIT clause is used in the SELECT statement to constrain the number of rows in a result set. The LIMIT clause accepts one or two arguments. The values of both arguments must be zero or positive integers.
The following illustrates the LIMIT clause syntax with two arguments:
SELECT
column1,column2,...
FROM
table
LIMIT offset, count;
Let’s examine the LIMIT clause parameters:
The offset specifies the offset of the first row to return. The offset of the first row is 0, not 1.
The count specifies the maximum number of rows to return.
When you use LIMIT with one argument, this argument will be used to specifies the maximum number of rows to return from the beginning of the result set.
SELECT
column1,column2,...
FROM
table
LIMIT count;