181題目地址:https://oj.leetcode.com/problems/employees-earning-more-than-their-managers/
181題又是一個簡單題目,給定一個Employee表,里面存儲了雇員的工資信息,包括名字、工資、經理ID,題目要求寫一個sql查找出所有那些自身工資比經理還高的雇員的名字。
+----+-------+--------+-----------+
| Id | Name | Salary | ManagerId |
+----+-------+--------+-----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
+----+-------+--------+-----------+
這個題目很簡單,現有表不能做就是因為現有的一行記錄里沒有包含經理的工資信息,但是有經理的ID,那么我們做一下關聯,把工資信息拿到,再過濾就好了,于是思路sql如下:
select
Name as Employee
from(
select
o1.Name
,o1.Salary as s
,o2.Salary as m
from(
select * from Employee
)o1
join(
select * from Employee
)o2
on(o1.ManagerId=o2.Id)
)t
where s>m
其中s是自己的工資,m是經理的工資~~一目了然
182題目地址:https://oj.leetcode.com/problems/duplicate-emails/
182也是Easy級別題目,題目描述就是寫一個sql,把Person表中有重復Email的記錄拉出來。
+----+---------+
| Id | Email |
+----+---------+
| 1 | a@b.com |
| 2 | c@d.com |
| 3 | a@b.com |
+----+---------+
很容易想到的思路:按照email做聚合,把count>1的取出來,對應sql如下:
select
Email
from(
select
Email
,count(Id) as cnt
from Person
group by Email
)t
where cnt>1
183題目地址:https://oj.leetcode.com/problems/customers-who-never-order/
183題,一個網站包含兩張表,一張Customers表存放客戶數據,一張Orders表存放產生訂單的客戶ID,題目要求寫sql查出沒有在網站產生過訂單的客戶。說白了就是查詢在Customers里而不在Orders里的數據,sql如下:
select
o1.Name as Customers
from(
select * from Customers
)o1
left outer join(
select * from Orders
)o2
on(o1.Id=o2.CustomerId )
where o2.CustomerId is null
3個簡單題目,夯實sql基礎~~