leetcode數據庫題目記錄(一)

(1)連接表
在這裏插入圖片描述
可以使用外連接進行查詢

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

(2)第二高的薪水
在這裏插入圖片描述
select distinct 檢索不同的列
limit 1,1 返回從行1開始的1行

select (select distinct salary from Employee
order by salary desc limit 1,1) as SecondHighestSalary 

(3)超過經理收入的員工
在這裏插入圖片描述
這一題可以使用自連接,自連接的結果就是兩張表的笛卡兒積,然後再把滿足條件的列篩選出來就可以了,笛卡兒積的結果如下:
笛卡兒積的結果

select
     a.Name as Employee 
From 
	Employee as a,Employee as b
where
	 a.ManagerId=b.Id and a.Salary>b.Salary

(4)查找重複的郵箱
在這裏插入圖片描述
這個可以使用分組過濾,對每個郵箱統計數目,並把數目大於2的郵箱過濾出來

select email from Person group by email having count(email) >1

(5)查找從不訂購的客戶
在這裏插入圖片描述
可以使用左連接,然後過濾出CustomerId爲空的客戶

select
     Customers.name as Customers
 from 
    Customers left outer join Orders On Customers.id=Orders.CustomerId
where 
    Orders.CustomerId is null

(6)分數排名
在這裏插入圖片描述
在這裏插入圖片描述

select a.score,
	(select count(distinct b.score) from scores b where b.score >=a.score) as Rank
from
	scores a order by a.score desc
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章