2019-04-11 数据库题目以及解法

一、第二高的薪水

1、题意

编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。

+---------------------+
| SecondHighestSalary |
+---------------------+
| 200                 |
+---------------------+

2、mysql解法

SELECT
  IFNULL(
(SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC
LIMIT 1 OFFSET 1),
NULL) AS SecondHighestSalary

3、小记

a、DISTINCT 是去重的意思
b、LIMIT 是查出几条数据
c、OFFSET 是从第几条数据开始。

二、第N高的薪水

1、题意

编写一个 SQL 查询,获取 Employee 表中第 高的薪水(Salary)。

+----+--------+
| Id | Salary |
+----+--------+
| 1  | 100    |
| 2  | 200    |
| 3  | 300    |
+----+--------+

例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 高的薪水,那么查询应返回 null

+------------------------+
| getNthHighestSalary(2) |
+------------------------+
| 200                    |
+------------------------+

2、mysql解法:函数形式

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN SET N
=N-1; RETURN ( # Write your MySQL query statement below. SELECT IFNULL( (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET N), NULL) AS SecondHighestSalary ); END

3、小记

  a、select  getNthHighestSalary(3) 调用函数

 

三、分数排名

1、题意

编写一个 SQL 查询来实现分数排名。如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。

+----+-------+
| Id | Score |
+----+-------+
| 1  | 3.50  |
| 2  | 3.65  |
| 3  | 4.00  |
| 4  | 3.85  |
| 5  | 4.00  |
| 6  | 3.65  |
+----+-------+

例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):

+-------+------+
| Score | Rank |
+-------+------+
| 4.00  | 1    |
| 4.00  | 1    |
| 3.85  | 2    |
| 3.65  | 3    |
| 3.65  | 3    |
| 3.50  | 4    |
+-------+------+

2、mysql解法

SELECT Score, 
(SELECT count(DISTINCT score) FROM Scores WHERE score >= s.Score) AS Rank 
FROM Scores s 
ORDER BY Score DESC ;

3、小记

  a、运用子查询,对 Scores s 中的每一个score进行对比。

   b、这个排名方法一定要熟记,基本很多地方能用到。

  c、运用“DISTINCT”这个,会将排名连续,,,,,1,2,2,3  ,而不是1,3,3,4

 四、查找重复的电子邮箱

1、题意:

编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。

示例:

+----+---------+
| Id | Email   |
+----+---------+
| 1  | a@b.com |
| 2  | c@d.com |
| 3  | a@b.com |
+----+---------+

根据以上输入,你的查询应返回以下结果:

+---------+
| Email   |
+---------+
| a@b.com |
+---------+

说明:所有电子邮箱都是小写字母。

2、mysql解法:

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

3、小记:

   记录这个,主要是不要让自己忘记 “having” 的用法

 

五、从不订购的客户

1、题意:

某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。

Customers 表:

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

Orders 表:

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

例如给定上述表格,你的查询应返回:

+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

2、mysql解法:

  a、

SELECT a.name customers FROM `customers` a left join  orders b on a.id=b.customerid 
where b.customerId is null

  b、

select customers.name as 'Customers'
from customers
where customers.id not in
(
    select customerid from orders
);

3、小记:

  a、判断是否为空,用 is null 、is not null

  b、学到not in 操作

 

 

六、部门工资第三高的员工

1、题意:

Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id 。

+----+-------+--------+--------------+
| Id | Name  | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1  | Joe   | 70000  | 1            |
| 2  | Henry | 80000  | 2            |
| 3  | Sam   | 60000  | 2            |
| 4  | Max   | 90000  | 1            |
| 5  | Janet | 69000  | 1            |
| 6  | Randy | 85000  | 1            |
+----+-------+--------+--------------+

Department 表包含公司所有部门的信息。

+----+----------+
| Id | Name     |
+----+----------+
| 1  | IT       |
| 2  | Sales    |
+----+----------+

编写一个 SQL 查询,找出每个部门工资前三高的员工。例如,根据上述给定的表格,查询结果应返回:

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

2、mysql解法:

select b.name Department ,c.name  Employee ,c.Salary Salary from department b ,
(
select id,name,Salary,departmentId,( select count(DISTINCT Salary) cou from  employee where Salary>=a.Salary and departmentId=a.departmentId ) rank from employee a
) c
where  b.id =c.departmentId and c.rank<4
order by c.departmentId,c.rank asc

解法思路:a、先将工资排序,再加上一个条件(按照不同部门的来将工资排序)。

  b、然后再查出排名<4的数据

3、小记:

  a、写sql的时候,对于比较复杂的,先弄出一部分来,再一点点补充。 

 

七、上升的温度

1、题意:

给定一个 Weather 表,编写一个 SQL 查询,来查找与之前(昨天的)日期相比温度更高的所有日期的 Id。

+---------+------------------+------------------+
| Id(INT) | RecordDate(DATE) | Temperature(INT) |
+---------+------------------+------------------+
|       1 |       2015-01-01 |               10 |
|       2 |       2015-01-02 |               25 |
|       3 |       2015-01-03 |               20 |
|       4 |       2015-01-04 |               30 |
+---------+------------------+------------------+

例如,根据上述给定的 Weather 表格,返回如下 Id:

+----+
| Id |
+----+
|  2 |
|  4 |
+----+

2、mysql解法:

  a、 网站的解法,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
;

  b、自己的解法,运用 date_sub(recorddate,interval -1 day) ,表示利用date_sub()函数计算出 recorddate(如:"2018-05-02") 后一天的日期

date_sub('2016-08-01',interval 1 day) 表示 2016-07-31
date_sub('2016-08-01',interval 0 day) 表示 2016-08-01
date_sub('2016-08-01',interval -1 day) 表示 2016-08-02
select a.id Id  from weather a ,(
    select *, date_sub(recorddate,interval -1 day) as predate  from weather 
)b
where  b.predate=a.RecordDate and a.temperature>b.temperature

  3、小记:熟练运用mysql自带的函数,可以起到很好的效果。

八、换座位

1、题意:

小美是一所中学的信息科技老师,她有一张 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  |
+---------+---------+

注意:

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

2、mysql解法:

  a、运用if(a,b,c) 如果a为true,则用b,否则为c。

select  if( id%2=0,id-1,if(id=(select  max(id) from seat),id,id+1))  as id,student from seat  order by id

  b、运用case

SELECT (CASE 
            WHEN MOD(id,2) = 1 AND id = (SELECT COUNT(*) FROM seat) THEN id
            WHEN MOD(id,2) = 1 THEN id+1
            ElSE id-1
        END) AS id, student
FROM seat
ORDER BY id;

3、小记:

   a、学会if、case语句吧,虽然以前也用过,忘记了一些

 

九、行程与用户

1、题意:

Trips 表中存所有出租车的行程信息。每段行程有唯一键 Id,Client_Id 和 Driver_Id 是 Users 表中 Users_Id 的外键。Status 是枚举类型,枚举成员为 (‘completed’, ‘cancelled_by_driver’, ‘cancelled_by_client’)。

+----+-----------+-----------+---------+--------------------+----------+
| Id | Client_Id | Driver_Id | City_Id |        Status      |Request_at|
+----+-----------+-----------+---------+--------------------+----------+
| 1  |     1     |    10     |    1    |     completed      |2013-10-01|
| 2  |     2     |    11     |    1    | cancelled_by_driver|2013-10-01|
| 3  |     3     |    12     |    6    |     completed      |2013-10-01|
| 4  |     4     |    13     |    6    | cancelled_by_client|2013-10-01|
| 5  |     1     |    10     |    1    |     completed      |2013-10-02|
| 6  |     2     |    11     |    6    |     completed      |2013-10-02|
| 7  |     3     |    12     |    6    |     completed      |2013-10-02|
| 8  |     2     |    12     |    12   |     completed      |2013-10-03|
| 9  |     3     |    10     |    12   |     completed      |2013-10-03| 
| 10 |     4     |    13     |    12   | cancelled_by_driver|2013-10-03|
+----+-----------+-----------+---------+--------------------+----------+

Users 表存所有用户。每个用户有唯一键 Users_Id。Banned 表示这个用户是否被禁止,Role 则是一个表示(‘client’, ‘driver’, ‘partner’)的枚举类型。

+----------+--------+--------+
| Users_Id | Banned |  Role  |
+----------+--------+--------+
|    1     |   No   | client |
|    2     |   Yes  | client |
|    3     |   No   | client |
|    4     |   No   | client |
|    10    |   No   | driver |
|    11    |   No   | driver |
|    12    |   No   | driver |
|    13    |   No   | driver |
+----------+--------+--------+

写一段 SQL 语句查出 2013年10月1日 至 2013年10月3日 期间非禁止用户的取消率。基于上表,你的 SQL 语句应返回如下结果,取消率(Cancellation Rate)保留两位小数。

+------------+-------------------+
|     Day    | Cancellation Rate |
+------------+-------------------+
| 2013-10-01 |       0.33        |
| 2013-10-02 |       0.00        |
| 2013-10-03 |       0.50        |
+------------+-------------------+

2、mysql解法:

SELECT
    a.Request_at AS DAY,
    ROUND( sum( CASE WHEN a.STATUS != "completed" THEN 1 ELSE 0 END ) / count( a.id ), 2 ) AS "Cancellation Rate"
FROM
    Trips a
    LEFT JOIN Users b ON a.client_id = b.users_id 
WHERE
    b.Banned = "No" 
    AND a.Request_at BETWEEN "2013-10-01" 
    AND "2013-10-03" 
GROUP BY
    a.Request_at

3、小记:

 学会 CASE WHEN a.STATUS != "completed" THEN 1 ELSE 0 END

四、查找重复的电子邮箱

1、题意:

2、mysql解法:

3、小记:

 

 感谢 https://leetcode-cn.com 网的数据库题库!!

 

 十、面试过程的笔试题

1、题意:查询有2门及以上不及格科目的学生姓名及其平均成绩

表结构  s(sid (学生id), sname (学生名字)) ,sc(sid(学生id),cid(课程id),grade(课程成绩))

2、mysql解法

select s.sname,avg(grade)
from s,sc 
where s.sid=sc.sid 
group by sname
having  sum(grade<60)>=2

运用好group by 跟having 

3、第二种解法,分步骤

思路:

#1 计算平均分
select sid,avg(grade) from sc group by sid;

#2 每个人的挂科数目
select sid,grade< 60 from sc;

#3 统计每个人的挂科数目
select sid,sum(grade< 60) from sc group by sid;

#4 在#3添加条件挂科数目大于等于2并且平均分小于60

select s.sid,sum(grade<60) as gk ,avg(sc.grade) from s,sc
where s.sid=sc.sid
GROUP BY s.sid
HAVING gk>=2

 



 

 

 

 

 

 

 

 

 

 

 

 

 




posted @ 2019-04-11 11:27  math_lin  阅读(275)  评论(0编辑  收藏  举报