leetcode刷题记录---数据库篇---19/10/9

数据库关键字:distinct去重,放于列前,用于所有的列,不能部分使用

top关键字限制返回的行。sql server中select top 5 name限制。oracle用where rownum = 5限制。mysql用limit 5限制。

limit 5 offset 6从第5行开始往后6行,也写作limit 6,5.注意sql必知必会上的这个地方说法有歧义,刷的题中用法相反

排序检索出来的数据:select from order by。。。注意order by必须作为查询语句的最后一行,后面可以跟多个属性列,比如先按价格排,再按名字排。。。默认A-Z,如果要降序,要加DESC(可针对每一个属性)关键字在属性后。

 

过滤数据:where关键字,<>不等于可以和!=互换。between 5 and 10。。。where number is null查询电话号码为空的记录。

高级数据过滤:OR和AND相反,并且AND关键字优先级较高,应该使用圆括号消除歧义。IN和or相像,但是in效率更高,并且in能包含其他的select语句,能更加动态的简历where字句。

NOT用法where not id = ‘1001’就等价于where id <> '1001',在复杂句子中not很常用,和in联合使用。

 

用通配符进行过滤:%表示任何字符出现任意次数,where name like 'Fish%'找出以Fish开头的词。

通配符%看起来可以匹配任何东西,但是有个例外,就是NULL,例如where name like '%'就不会匹配产品名称为NULL的行。

_匹配单个字符,[]通配符,指定一个字符集,比如where name like '[JM]%'意思是找出以J或者M开头的名字。他可以用^l来表示否定:where name like '[^JM]%'

 

7.2创建计算字段


1.组合两个表175

题目描述:编写查询,满足无论person是否有地址信息,都要基于量表提供person一下信息

FirstName, LastName, City, State

知识点:

innner join是两个表的交集。

outer join又分为

left join:产生A的完全集,B中匹配才有值

right join:产生B的完全集,A中匹配 才有值

fulll join:产生A和B的并集

cross join是指把表A和表B的数据进行N*M组合,即笛卡尔积

注意,如果没有某个人的地址信息,使用where子句将会过滤失败,因为不会显示姓名信息

on和where的区别:

不管on上的条件是否为真,都会返回left或者right表中的记录

# Write your MySQL query statement below
select FirstName, LastName, City, State
from Person left join Address
on Person.Personid = Address.Personid;

2.第二高的薪水

疑惑点:万一表中只有一条数据,那么可以将查询出来的表作为临时表?先死记住临时表在这里这样用。

SELECT DISTINCT
    Salary AS SecondHighestSalary
FROM
    Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1
//上述方法不行,因为如果没有第二高工资,那么将会判定为错误答案。
//可以将它作为临时表

select 
    (select distinct salary
     from Employee
     order by Salary DESC
     limit 1 offset 1) as SecondHighestSalary;

//解决NULL问题的另一种方法是使用“IFNULL”函数

select ifnull((select distinct salary
     from Employee
     order by Salary DESC
     limit 1 offset 1),null) as SecondHighestSalary;

3.第N高的薪水

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  DECLARE P INT;
  DECLARE Q INT;
  IF(N<1)
    THEN SET P = 0,Q = 0;
  ELSE 
    SET P = N-1,Q =1;
  END IF;
  RETURN (
      # Write your MySQL query statement below.
      SELECT IFNULL(
          (SELECT DISTINCT Salary
          FROM Employee
          ORDER BY Salary DESC
          LIMIT P,Q),NULL
      )AS getNthHighestSalary
  );
END

4.分数排名

# Write your MySQL query statement below
select a.Score,(
select count(distinct b.Score)
from Scores b
where b.Score>=a.Score
)as rank
from Scores a
order by Score desc;

5.连续出现的数字

连续出现3次,意味着相同数字的id是连续的,可使用logs并检查是否有3个连续的相同数字。

//用distinct和where语句来做
# Write your MySQL query statement below
select distinct 
    l1.Num as ConsecutiveNums
from 
    Logs l1,Logs l2,Logs l3
where 
    l1.Id=l2.Id-1
    and l2.Id = l3.Id -1
    and l1.Num = l2.Num
    and l2.Num = l3.NumNum

6.超过经理收入的员工

SELECT
    a.Name AS 'Employee'
FROM
    Employee AS a,
    Employee AS b
WHERE
    a.ManagerId = b.Id
        AND a.Salary > b.Salary

7.查找重复的电子邮箱

select distinct l1.Email as Email
from Person l1,Person l2
where l1.Id <> l2.Id
    and l1.Email = l2.Email;



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


select Email
from (select Email,count(Email) as num
    from Person
    group by Email
 ) as static
where num>1

8.从不订购的客户

# Write your MySQL query statement below
select Customers.Name as 'Customers'
from Customers
where Customers.Id not in
(select CustomerId from Orders);

9.部门工资最高的员工

# Write your MySQL query statement below
select Department.name as Department,
       Employee.name as Employee,
       Salary
from Employee join Department on (Department.Id = Employee.DepartmentId)
where (Employee.DepartmentId,Salary) in 
    (select DepartmentId,max(Salary)
    from Employee
    group by DepartmentId);

10.删除重复的电子邮箱

心路历程:从两个表找出email相同的元素,并且只留下id最小的。where p1.Id > p2.Id and p1.Email = p2.Email

delete p1
from Person p1,Person p2
where p1.Id>p2.Id and p1.Email = p2.Email;

11.上升的温度

mysql使用DATEDIFF来比较两个日期类型的值,因此可通过将weather与自身相结合,并使用DATEDIFF()函数

select weather.id as 'Id'
from 
weather join weather w on DATEDIFF(weather.date,w.date) = 1
and weather.Temperature > w.Temperature

12.部门工资前三高的所有员工

公司前3高的薪水意味着有不超过3个工资比这个值大。

/*Employee 表包含所有员工信息,每个员工有其对应的工号 Id,姓名 Name,工资 Salary 和部门编号 DepartmentId 。

+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 85000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
| 7  | Will  | 70000  | 1            |
+----+-------+--------+--------------+
Department 表包含公司所有部门的信息。

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+
编写一个 SQL 查询,找出每个部门获得前三高工资的所有员工。例如,根据上述给定的表,查询结果应返回:

+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT         | Max      | 90000  |
| IT         | Randy    | 85000  |
| IT         | Joe      | 85000  |
| IT         | Will     | 70000  |
| Sales      | Henry    | 80000  |
| Sales      | Sam      | 60000  |
+------------+----------+--------+
解释:

IT 部门中,Max 获得了最高的工资,Randy 和 Joe 都拿到了第二高的工资,Will 的工资排第三。销售部门(Sales)只有两名员工,Henry 的工资最高,Sam 的工资排第二。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/department-top-three-salaries
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/



SELECT
	Department.NAME AS Department,
	e1.NAME AS Employee,
	e1.Salary AS Salary 
FROM
	Employee AS e1,Department 
WHERE
	e1.DepartmentId = Department.Id 
	AND 3 > (SELECT  count( DISTINCT e2.Salary ) 
			 FROM	Employee AS e2 
			 WHERE	e1.Salary < e2.Salary 	AND e1.DepartmentId = e2.DepartmentId 	) 
ORDER BY Department.NAME,Salary DESC;

 

 

 

620.有趣的电影

/*某城市开了一家新的电影院,吸引了很多人过来看电影。该电影院特别注意用户体验,专门有个 LED显示板做电影推荐,上面公布着影评和相关电影描述。

作为该电影院的信息部主管,您需要编写一个 SQL查询,找出所有影片描述为非 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列。

 

例如,下表 cinema:

+---------+-----------+--------------+-----------+
|   id    | movie     |  description |  rating   |
+---------+-----------+--------------+-----------+
|   1     | War       |   great 3D   |   8.9     |
|   2     | Science   |   fiction    |   8.5     |
|   3     | irish     |   boring     |   6.2     |
|   4     | Ice song  |   Fantacy    |   8.6     |
|   5     | House card|   Interesting|   9.1     |
+---------+-----------+--------------+-----------+
对于上面的例子,则正确的输出是为:

+---------+-----------+--------------+-----------+
|   id    | movie     |  description |  rating   |
+---------+-----------+--------------+-----------+
|   5     | House card|   Interesting|   9.1     |
|   1     | War       |   great 3D   |   8.9     |
+---------+-----------+--------------+-----------+

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/not-boring-movies
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/






select *
from cinema
where mod(id,2) = 1 and description != 'boring'
order by rating DESC
;

627.交换工资

/*给定一个 salary 表,如下所示,有 m = 男性 和 f = 女性 的值。交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求只使用一个更新(Update)语句,并且没有中间的临时表。

注意,您必只能写一个 Update 语句,请不要编写任何 Select 语句。

例如:

| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | m   | 2500   |
| 2  | B    | f   | 1500   |
| 3  | C    | m   | 5500   |
| 4  | D    | f   | 500    |
运行你所编写的更新语句之后,将会得到以下表:

| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-salary
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/


update salary
SET 
    sex = case sex
    when 'm' then 'f'
    else 'm'
    end;

595.大的国家

/*这里有张 World 表

+-----------------+------------+------------+--------------+---------------+
| name            | continent  | area       | population   | gdp           |
+-----------------+------------+------------+--------------+---------------+
| Afghanistan     | Asia       | 652230     | 25500100     | 20343000      |
| Albania         | Europe     | 28748      | 2831741      | 12960000      |
| Algeria         | Africa     | 2381741    | 37100000     | 188681000     |
| Andorra         | Europe     | 468        | 78115        | 3712000       |
| Angola          | Africa     | 1246700    | 20609294     | 100990000     |
+-----------------+------------+------------+--------------+---------------+
如果一个国家的面积超过300万平方公里,或者人口超过2500万,那么这个国家就是大国家。

编写一个SQL查询,输出表中所有大国家的名称、人口和面积。

例如,根据上表,我们应该输出:

+--------------+-------------+--------------+
| name         | population  | area         |
+--------------+-------------+--------------+
| Afghanistan  | 25500100    | 652230       |
| Algeria      | 37100000    | 2381741      |
+--------------+-------------+--------------+

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/big-countries
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/

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

626.换座位

/*小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。

其中纵列的 id 是连续递增的

小美想改变相邻俩学生的座位。

你能不能帮她写一个 SQL query 来输出小美想要的结果呢?

 

示例:

+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Abbot   |
|    2    | Doris   |
|    3    | Emerson |
|    4    | Green   |
|    5    | Jeames  |
+---------+---------+
假如数据输入的是上表,则输出结果如下:

+---------+---------+
|    id   | student |
+---------+---------+
|    1    | Doris   |
|    2    | Abbot   |
|    3    | Green   |
|    4    | Emerson |
|    5    | Jeames  |
+---------+---------+
注意:

如果学生人数是奇数,则不需要改变最后一个同学的座位。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/exchange-seats
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/



select (
    case
        when mod(id,2) != 0 and counts != id then id+1
        when mod(id,2) != 0 and counts =id then id
        else id -1
    end
    )as id,student

from seat,(
    select count(*) as counts from seat
) as count_seats

order by id ASC

596.超过5名学生的课

/*有一个courses 表 ,有: student (学生) 和 class (课程)。

请列出所有超过或等于5名学生的课。

例如,表:

+---------+------------+
| student | class      |
+---------+------------+
| A       | Math       |
| B       | English    |
| C       | Math       |
| D       | Biology    |
| E       | Math       |
| F       | Computer   |
| G       | Math       |
| H       | Math       |
| I       | Math       |
+---------+------------+
应该输出:

+---------+
| class   |
+---------+
| Math    |
+---------+
Note:
学生在每个课中不应被重复计算。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/classes-more-than-5-students
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。*/





select class

from 
(select class,count(distinct student)as counts
from courses
group by class) as e1

where counts >= 5 

1179.重新格式化部门表

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(刷题)