1. 程式人生 > >SQL練習總結

SQL練習總結

是否 客戶 ssi sam last 總結 manage 查詢 join

【SQL語句練習】

1.

表1: Person

+-------------+---------+
| 列名         | 類型     |
+-------------+---------+
| PersonId    | int     |
| FirstName   | varchar |
| LastName    | varchar |
+-------------+---------+
PersonId 是上表主鍵

表2: Address

+-------------+---------+
| 列名         | 類型    |
+-------------+---------+
| AddressId   | int     |
| PersonId    | int     |
| City        | varchar |
| State       | varchar |
+-------------+---------+
AddressId 是上表主鍵

編寫一個 SQL 查詢,滿足條件:無論 person 是否有地址信息,都需要基於上述兩表提供 person 的以下信息:

FirstName, LastName, City, State

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

2.

Employee 表包含所有員工,他們的經理也屬於員工。每個員工都有一個 Id,此外還有一列對應員工的經理的 Id。

+----+-------+--------+-----------+
| Id | Name  | Salary | ManagerId |
+----+-------+--------+-----------+
| 1  | Joe   | 70000  | 3         |
| 2  | Henry | 80000  | 4         |
| 3  | Sam   | 60000  | NULL      |
| 4  | Max   | 90000  | NULL      |
+----+-------+--------+-----------+

給定 Employee 表,編寫一個 SQL 查詢,該查詢可以獲取收入超過他們經理的員工的姓名。在上面的表格中,Joe 是唯一一個收入超過他的經理的員工。

+----------+
| Employee |
+----------+
| Joe      |
+----------+

select e1.name as Employee from Employee e1 inner join Employee e2 on e1.ManagerId = e2.Id where e1.Salary > e2.Salary

3.

某網站包含兩個表,Customers

表和 Orders 表。編寫一個 SQL 查詢,找出所有從不訂購任何東西的客戶。

Customers 表:

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

Orders 表:

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

例如給定上述表格,你的查詢應返回:

+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+
select Name as Customers from Customers where Id not in (select CustomerId from Orders)



SQL練習總結