1、表聯合
Table1: Person (PersonId is the primary key column for this table.)
Column Name | Type |
---|---|
PersonId | int |
FirstName | varchar |
LastName | varchar |
Table2: Address (AddressId is the primary key column for this table.)
Column Name | Type |
---|---|
AddressId | int |
PersonId | int |
City | varchar |
State | varchar |
用這兩張表輸出 FirstName, LastName, City, State四個字段,無論PersonId是否爲空。
select person.FirstName,person.LastName,Address.City,Address.State
from Person left join Address
on Person.PersonId = Address.PersonId
2、 Second Highest Salary
table:employee
Id | Salary |
---|---|
1 | 100 |
2 | 200 |
3 | 300 |
question: give the second highest salary.If there is no second highest salary, then the query should return null.
求排名第二的工資,如果沒有,返回NULL。
##用LIMIT限定數據記錄查詢數量
SELECT DISTINCT Salary AS SecondHighestSalary
FROM Employee
ORDER BY Salary
LIMIT 1,1
以上寫法沒有考慮到 不存在第二位的情況,例如只有一條數據記錄。這時把以上查詢的結果作爲臨時表。
SELECT *
FROM(
SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary
LIMIT 1,1) AS SecondHighestSalary
另一種解法:
SELECT MAX(Salary) as SecondHighestSalary FROM Employee
WHERE Salary NOT IN(SELECT MAX(Salary) from Employee)
3、Department Highest Salary
table1:The Employee table holds all employees
Id | Name | Salary | DepartmentId |
---|---|---|---|
1 | Joe | 70000 | 1 |
2 | Henry | 80000 | 2 |
3 | Sam | 60000 | 2 |
4 | Max | 90000 | 1 |
table2:The Department table holds all departments of the company.
Id | Name |
---|---|
1 | IT |
2 | Sales |
查找每個部門的最高工資,如下:
Department | Employee | Salary |
---|---|---|
IT | Max | 90000 |
Sales | Henry | 80000 |
SELECT Department.Name AS Department,A.Name AS Employee,A.Salary AS Salary
FROM
(SELECT Name, MAX(Salary) AS Salary,DepartmentId
FROM employee GROUP BY DepartmentId) A
LEFT JOIN Department
ON A.DepartmentId = Department.Id
結果出錯:
SELECT Name, MAX(Salary) AS Salary,DepartmentId
FROM employee GROUP BY DepartmentId
按照DepartmentId分組後,每組如果有多個員工有相同的最高工資,而MAX只返回一個員工Name。
1.先聯合兩表,找出各個部門的最高薪水
SELECT Department.Id, Department.Name, MAX(Salary) AS Salary
FROM employee JOIN Department
ON employee.DepartmentId = Department.Id
GROUP BY Department.Id
2. 與僱員表聯合,匹配出該工資的員工,這樣就包括每組有多個員工有相同的最高工資的情況。
SELECT t.Name AS Department, e.Name AS Employee, t.Salary
FROM
(SELECT Department.Id,
Department.Name AS Name,
MAX(Salary) AS Salary
FROM Employee JOIN Department
ON Employee.DepartmentId = Department.Id
GROUP BY Department.Id
) t
JOIN Employee e
ON t.Id=e.DepartmentId and t.Salary=e.Salary