177. nth highest salary
create function getnthhighestsalary(n int) returns int
begin
declare m int; #宣告區域性變數
set m = n-1; #賦值,因為limit 後面的引數不能是乙個表示式
return (
# write your mysql query statement below.
select distinct salary
from employee
order by salary desc
limit m,1
);end
因為這個題目需要完成的只是定義函式,所以可以不用ifnull()或者coalesce()來判斷返回值是不是非空,如果返回空值,在呼叫函式時再解決
178
. rank scores
# write your mysql query statement below
select c.score as score, r as rank
from scores c join (select a.score as score, @i:=@i+1 as r
from (select distinct score from scores) as a,(select @i:=0) as b
order by a.score desc) as t
on c.score = t.score
order by c.score desc;
思路是先把去重後的成績排序生成新錶t,然後將原始表c 和新錶t 根據對應成績聯接,則相同的成績就會有相同的排序
注意生成排序的方法是定義了乙個自增的變數,然後用select 賦值為0(select 賦值時要用 :=)
其他方法:(比較常見的方法)
# write your mysql query statement below
select a.score as score, count(distinct b.score) as rank
from scores a,scores b
where a.score<=b.score
group by a.id,a.score
order by a.score desc
重點是a.score<=b.score
這裡,通過計算去重後的大於等於a.score的資料的個數來給a.score排序
180
. consecutive numbers
select c.num as consecutivenums
from logs a join logs b on b.id = (a.id+1) and b.num = a.num
join logs c on c.id = (b.id+1) and c.num = b.num
group by c.num
注意方法
184
. department highest salary
select d.name as department, e.name as employee, e.salary as salary
from employee e join department d on e.departmentid = d.id
where e.salary in (select max(a.salary)
from employee a
where a.departmentid = e.departmentid
)
注意不能直接查詢
d.name,e.name,max(salary).......group by d.name,因為group by 只返回分組後的一條資料,如果這樣做,會預設取查詢到的第乙個e.name,而不是max(salary) 對應的 e.name
185. department top three salaries
# write your mysql query statement below
select d.name as department, e.name as employee, e.salary as salary
from employee e join department d on e.departmentid = d.id
where e.salary >=coalesce ((select distinct a.salary
from employee a
where e.departmentid = a.departmentid
order by a.salary desc
limit 2,1),0) # mysql中 in 和 limit 不能連用
order by d.id,e.salary desc
思路是找出每個部門排第三的薪水對應的記錄,然後查詢》=這個薪水的記錄
注意mysql中,limit和in 不能連用,但是和比較運算子可以一塊用,此外在一些問題中還可以用建個臨時表的方法來解決limit和in不能連用的問題
leetcode刷題記錄
我覺得每天來兩道,練習練習,再看看人家是怎麼優化的。1.給定乙個整數陣列 nums 和乙個目標值 target,請你在該陣列中找出和為目標值的那 兩個 整數,並返回他們的陣列下標。c 暴力求解,204ms,9.1m class solution for index,num in enumerate ...
LeetCode刷題記錄
動態規劃和貪心演算法的異同點 class solution throw newruntimeexception 時間複雜度 o n 2 對於每個元素,我們試圖通過遍歷陣列的其餘部分來尋找它所對應的目標元素,這將耗費 o n o n 的時間。因此時間複雜度為 o n 2 需要一種方法,尋找符合要求的元...
leetcode刷題記錄
工作之餘刷刷題排解下寂寞 1 面試題66.構建乘積陣列 解題思路 題目要求可以簡化為求陣列中任意乙個元素左右兩邊所有元素的乘積。偷懶就用了乙個套路,練習了p c c python class solution def constructarr self,a list int list int 除法是...