SQL in leetcode——easy篇

1.https://leetcode.com/problems/big-countries/

最简单的有条件的筛选:

select name, population, area from World where area > 3000000 or population > 25000000

2.https://leetcode.com/problems/swap-salary/:swap列值的属性:

考查update或select的用法,swap这个if函数,有点类似C语言里面的“?:”操作

select id, name, if(sex = 'm','f','m') as sex, salary from salary

或update salary set sex=CHAR(ASCII('f')^ASCII('m')^ASCII(sex));#很妙的抑或操作,但是容易写错

3.https://leetcode.com/problems/not-boring-movies 考查排序操作order by(默认升序,逆序加desc)

select * from cinema where id % 2 and description != 'boring'

order by rating desc

4.https://leetcode.com/problems/duplicate-emails/ 考查去重操作:

a.GROUP BY 语句用于结合合计函数,根据一个或多个列对结果集进行分组。

b.having是分组(group by)后的筛选条件,分组后的数据组内再筛选

c.count:计数

d.distinct:去重

select distinct Email from Person where Email in (select Email from Person group by Email having count(Email) > 1)

5.https://leetcode.com/problems/combine-two-tables/ 考查两个表的join,又因为有“for each person in the Person table, regardless if there is an address for each of those people:” 可知考查的是left join。

select Person.FirstName, Person.Lastname, Address.City, Address.State

from Person left join Address

on Person.PersonId = Address.PersonId

6.https://leetcode.com/problems/employees-earning-more-than-their-managers/:考查同一个表的不同实例,通过join操作建立联系。小细节:最后table的列名发生了变化。

select e1.Name as Employee from Employee e1

join Employee e2 on e1.ManagerId = e2.Id

where e1.Salary > e2.Salary

7.https://leetcode.com/problems/customers-who-never-order/:考查left join操作(但是是差集),或者not in操作

ed0:

select Customers.Name as Customers

from Customers left join Orders

on Customers.Id = Orders.CustomerId where Orders.Id is null

ed1:

select Customers.Name as Customers from Customers

where Customers.Id not in (select CustomerId from Orders)

8.https://leetcode.com/problems/classes-more-than-5-students/:考查group by

select class from courses group by class

having count(distinct(student)) >= 5

9.https://leetcode.com/problems/rising-temperature/ 依然是考查两个实例用法,还有时间差的用法 datediff

select e1.Id from Weather e1, Weather e2

where datediff(e1.RecordDate, e2.RecordDate) = 1 and e1.Temperature > e2.Temperature

10.https://leetcode.com/problems/delete-duplicate-emails/ 删除重复邮箱,保留较小编号。考查delete用法。

delete p2 from Person p1, Person p2

where p1.Email = p2.Email and p1.Id < p2.Id

11.https://leetcode.com/problems/second-highest-salary/:第二高工资

a。最直观的做法,先select出最高的,然后再找出小于最大值的 最大值

select max(Salary) as SecondHighestSalary

from Employee

where salary < (select max(Salary) from Employee)

b。引入排序。复杂篇,下次再写。

你可能感兴趣的:(SQL in leetcode——easy篇)