leetcode刷题 --数据库(更新中。。。)

组合两个表:

题目链接

  • 解题思路:左连接
select FirstName, LastName, City, State 
from person natural left join address;
-- 或
select FirstName, LastName, City, State 
from person p left join address a on p.PersonID = a.PersonID

第二高的薪水:

题目链接

  • 解题思路:用distinct去除重复值,倒序排序之后再用limit选出第二高的
select distinct Salary as SecondHighestSalary 
from Employee 
order by Salary desc 
limit 1,1;

无语,做错了,题目要求如果不存在第二高的薪水,那么查询应返回 null,这里用IFNULL()函数来实现

select IFNULL((select distinct Salary
from Employee
order by Salary desc
limit 1,1),null) as SecondHighestSalary

分数排名:

题目链接

  • 解题思路:抄的,没想明白
select s1.Score, count(distinct(s2.score)) Rank
from Scores s1, Scores s2
where s1.score<=s2.score
group by s1.Id
order by Rank;

超过经理收入的员工:

题目链接

  • 解题思路:写个子查询就完事了
select Name Employee from Employee e
where Salary > (select Salary 
from Employee where Id = e.Managerid);

查找重复的电子邮箱:

题目链接

  • 解题思路:分组计数就完事了
select Email from person group by Email having count(Email)>1

从不订购的客户:

题目链接

  • 解题思路:用个<> all就完事了
select Name as Customers 
from Customers 
where id <> all (select customerId from orders);

删除重复的电子邮箱:

题目链接

  • 解题思路:删除重复的电子邮箱,并保存id最小的那个
delete p1 from person p1, person p2
where p1.Email = p2.Email and p1.Id > p2.Id;

上升的温度

题目链接

  • 解题思路:利用datediff()函数来表示今天昨天
SELECT w1.Id 
FROM Weather w1, Weather w2 
WHERE
	DATEDIFF( w1.RecordDate, w2.RecordDate ) = 1 
	AND 
    w1.Temperature > w2.Temperature

大的国家

题目链接

  • 解题思路:最简单的题了
select name, population, area from World where area > 3000000 or population > 25000000; 

超过5名学生的课:

题目链接

  • 解题思路:也不难,就是要注意可能有重复数据
select class from courses group by class 
having count(*) >= 5 and count(distinct student) = count(*)

行程和用户:

题目链接

  • 力扣说我错了,理由是:
    在这里插入图片描述
select request_at as Day, 
round (
(sum(case when status = 3 then 1 else 0 end) 
+ sum( case when status = 2 then 1 else 0 end )
)/count(status),2)
as 'Cancellatio Rate'
from trips t join users u on t.Client_Id = u.Users_Id and u.banned = 'No' GROUP BY Request_at;

发布了19 篇原创文章 · 获赞 20 · 访问量 9508

猜你喜欢

转载自blog.csdn.net/qq_39323164/article/details/104169557