LeetCode数据库练习题MySql
197. Rising Temperature
Total Accepted: 10265 Total Submissions: 40109 Difficulty: Easy
Given a Weather table, write a SQL query to find all dates' Ids with higher temperature compared to its previous (yesterday's) dates.
+---------+------------+------------------+
| Id(INT) | Date(DATE) | Temperature(INT) |
+---------+------------+------------------+
| 1 | 2015-01-01 | 10 |
| 2 | 2015-01-02 | 25 |
| 3 | 2015-01-03 | 20 |
| 4 | 2015-01-04 | 30 |
+---------+------------+------------------+
For example, return the following Ids for the above Weather table:
+----+
| Id |
+----+
| 2 |
| 4 |
+----+
# Write your MySQL query statement below
SELECT a.ID
FROM Weather a INNER JOIN Weather b
ON TO_DAYS(a.Date) = TO_DAYS(b.Date) + 1
WHERE a.Temperature > b.Temperature
=============================================================================================================================
196. Delete Duplicate Emails
Total Accepted: 8758 Total Submissions: 46490 Difficulty: Easy
Write a SQL query to delete all duplicate email entries in a table named Person, keeping only unique emails based on its smallest Id.
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
+----+------------------+
Id is the primary key column for this table.
For example, after running your query, the above Person table should have the following rows:
+----+------------------+
| Id | Email |
+----+------------------+
| 1 | [email protected] |
| 2 | [email protected] |
+----+------------------+
# Write your MySQL query statement below
DELETE FROM Person
WHERE Email IN (SELECT A.Email
FROM ( SELECT *
FROM Person
GROUP BY Email
HAVING count(Email) > 1) A)
AND ID NOT IN (SELECT B.ID
FROM ( SELECT min(ID) AS ID
FROM Person
GROUP BY Email
HAVING count(Email) > 1) B);
=====================================================================================================================
183. Customers Who Never Order
Total Accepted: 12950 Total Submissions: 38604 Difficulty: Easy
Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.
Table: Customers.
+----+-------+
| Id | Name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
Table: Orders.
+----+------------+
| Id | CustomerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
Using the above tables as example, return the following:
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
SELECT C.Name
FROM Customers C
WHERE C.ID NOT IN (SELECT O.CustomerId
FROM Orders O);
=======================================================================================
182. Duplicate Emails
Total Accepted: 13314 Total Submissions: 35281 Difficulty: Easy
Write a SQL query to find all duplicate emails in a table named Person.
+----+---------+
| Id | Email |
+----+---------+
| 1 | [email protected] |
| 2 | [email protected] |
| 3 | [email protected] |
+----+---------+
For example, your query should return the following for the above table:
+---------+
| Email |
+---------+
| [email protected] |
+---------+
Note: All emails are in lowercase.
# Write your MySQL query statement below
SELECT EMAIL
FROM Person
GROUP BY Email
HAVING count(Email) > 1
==================================================
181. Employees Earning More Than Their Managers
Total Accepted: 13732 Total Submissions: 33498 Difficulty: Easy
The Employee table holds all employees including their managers. Every employee has an Id, and there is also a column for the manager Id.
+----+-------+--------+-----------+
| Id | Name | Salary | ManagerId |
+----+-------+--------+-----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
+----+-------+--------+-----------+
Given the Employee table, write a SQL query that finds out employees who earn more than their managers. For the above table, Joe is the only employee who earns more than his manager.
+----------+
| Employee |
+----------+
| Joe |
+----------+
SELECT p.Name
FROM Employee p LEFT JOIN Employee q
ON p.ManagerId = q.Id
WHERE p.Salary > q.Salary;
--------------------------------------------------------------------------------------------------------
175. Combine Two Tables
Total Accepted: 15789 Total Submissions: 46540 Difficulty: Easy
Table: Person
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| PersonId | int |
| FirstName | varchar |
| LastName | varchar |
+-------------+---------+
PersonId is the primary key column for this table.
Table: Address
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| AddressId | int |
| PersonId | int |
| City | varchar |
| State | varchar |
+-------------+---------+
AddressId is the primary key column for this table.
Write a SQL query for a report that provides the following information for each person in the Person table, regardless if there is an address for each of those people:
FirstName, LastName, City, State
Subscribe to see which companies asked this question
# Write your MySQL query statement below
SELECT p.FirstName,
p.LastName,
a.City,
a.State
FROM Person p LEFT JOIN Address a ON p.PersonId = a.PersonId;
------------------------------------------------------------------------------------
176. Second Highest Salary
Total Accepted: 14338 Total Submissions: 58128 Difficulty: Easy
Write a SQL query to get the second highest salary from the Employee table.
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return null.
Subscribe to see which companies asked this question
# Write your MySQL query statement below
SELECT MAX(Salary)
FROM Employee
WHERE Salary <> (SELECT MAX(Salary) FROM Employee)
-------------------------------------------------------------------------------------
177. Nth Highest Salary
Total Accepted: 6729 Total Submissions: 41811 Difficulty: Medium
Write a SQL query to get the nth highest salary from the Employee table.
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
For example, given the above Employee table, the nth highest salary where n = 2 is 200. If there is no nth highest salary, then the query should return null.
Subscribe to see which companies asked this question
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
# Write your MySQL query statement below.
select IFNULL(Salary, NULL) Salary from (
select @row_num := @row_num+1 Rank, Salary from (
select Salary from Employee group by Salary desc
) t1 join (
select @row_num := 0 from dual
) t2
) t where t.Rank=N
);
END
-------------------------------------------------------------------------------------------------------
178. Rank Scores
Total Accepted: 7067 Total Submissions: 29272 Difficulty: Medium
Write a SQL query to rank scores. If there is a tie between two scores, both should have the same ranking. Note that after a tie, the next ranking number should be the next consecutive integer value. In other words, there should be no "holes" between ranks.
+----+-------+
| Id | Score |
+----+-------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
+----+-------+
For example, given the above Scores table, your query should generate the following report (order by highest score):
+-------+------+
| Score | Rank |
+-------+------+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
+-------+------+
Subscribe to see which companies asked this question
# Write your MySQL query statement below
SELECT Score, Rank FROM(
SELECT Score,
@curRank := @curRank + IF(@prevScore = Score, 0, 1) AS Rank, @prevScore := Score
FROM Scores s, (SELECT @curRank := 0) r, (SELECT @prevScore := NULL) p
ORDER BY Score DESC
) t;
SELECT Scores.Score, COUNT(Ranking.Score) AS RANK
FROM Scores
, (
SELECT DISTINCT Score
FROM Scores
) Ranking
WHERE Scores.Score <= Ranking.Score
GROUP BY Scores.Id, Scores.Score
ORDER BY Scores.Score DESC;
-----------------------------------------------------------------------------------------------------
180. Consecutive Numbers
Total Accepted: 6547 Total Submissions: 25150 Difficulty: Medium
Write a SQL query to find all numbers that appear at least three times consecutively.
+----+-----+
| Id | Num |
+----+-----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
+----+-----+
For example, given the above Logs table, 1 is the only number that appears consecutively for at least three times.
Subscribe to see which companies asked this question
# Write your MySQL query statement below
SELECT DISTINCT num
FROM (SELECT num, count(rank) AS count
FROM (SELECT num,
@curRank := @curRank + IF(@preNum = num, 0, 1) AS rank,
@preNum := num
FROM Logs s,
(SELECT @curRank := 0) r,
(SELECT @preNum := NULL) p) t
GROUP BY rank
HAVING count >= 3
) tmp;
SELECT DISTINCT num
FROM (SELECT num,
@curRank := @preRank + IF(@preNum = num, 1, 0),
@preRank := IF(@preNum = num, @curRank, 1) AS rank,
@preNum := num
FROM Logs s, (SELECT @preRank := 1) r, (SELECT @preNum := NULL) p) t
WHERE rank >= 3;
----------------------------------------------------------------------------------
184. Department Highest Salary
Total Accepted: 7621 Total Submissions: 40544 Difficulty: Medium
The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id.
+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 | Sam | 60000 | 2 |
| 4 | Max | 90000 | 1 |
+----+-------+--------+--------------+
The Department table holds all departments of the company.
+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+
Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, Max has the highest salary in the IT department and Henry has the highest salary in the Sales department.
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| Sales | Henry | 80000 |
+------------+----------+--------+
Subscribe to see which companies asked this question
SELECT t.Department, e.name AS 'Employee', e.salary
FROM Employee e
INNER JOIN
(SELECT d.id AS 'Departmentid',
d.name AS 'Department',
max(e.Salary) AS 'max'
FROM Employee e INNER JOIN Department d ON e.departmentid = d.id
GROUP BY d.name) t
ON e.departmentid = t.departmentid AND salary = max;
--------------------------------------------------------------------------------------------
185. Department Top Three Salaries
Total Accepted: 4778 Total Submissions: 32513 Difficulty: Hard
The Employee table holds all employees. Every employee has an Id, and there is also a column for the 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 |
+----+-------+--------+--------------+
The Department table holds all departments of the company.
+----+----------+
| Id | Name |
+----+----------+
| 1 | IT |
| 2 | Sales |
+----+----------+
Write a SQL query to find employees who earn the top three salaries in each of the department. For the above tables, your SQL query should return the following rows.
+------------+----------+--------+
| Department | Employee | Salary |
+------------+----------+--------+
| IT | Max | 90000 |
| IT | Randy | 85000 |
| IT | Joe | 70000 |
| Sales | Henry | 80000 |
| Sales | Sam | 60000 |
+------------+----------+--------+
Subscribe to see which companies asked this question
SELECT D.Name AS Department, E.Name AS Employee, E.Salary AS Salary
FROM Employee E, Department D
WHERE (SELECT COUNT(DISTINCT (Salary))
FROM Employee
WHERE DepartmentId = E.DepartmentId AND Salary > E.Salary) < 3
AND E.DepartmentId = D.Id
ORDER BY E.DepartmentId, E.Salary DESC;
SELECT d.NAME AS Department, t.NAME AS Employee, Salary
FROM (SELECT DepartmentId,
NAME,
Salary,
@rank :=
IF(@prevDeptId != DepartmentId,
1,
IF(@prevSalary = Salary, @rank, @rank + 1))
AS Rank,
@prevDeptId := DepartmentId AS prevDeptId,
@prevSalary := Salary AS prevSalary
FROM Employee e,
(SELECT @rank := 0, @prevDeptId := NULL, @prevSalary := NULL) r
ORDER BY DepartmentId ASC, Salary DESC) t
INNER JOIN
Department d
ON t.DepartmentId = d.ID
WHERE t.rank <= 3
----------------------------------------------------------------------------------------
262. Trips and Users
Total Accepted: 2133 Total Submissions: 13494 Difficulty: Hard
The Trips table holds all taxi trips. Each trip has a unique Id, while Client_Id and Driver_Id are both foreign keys to the Users_Id at the Users table. Status is an ENUM type of (‘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|
+----+-----------+-----------+---------+--------------------+----------+
The Users table holds all users. Each user has an unique Users_Id, and Role is an ENUM type of (‘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 |
+----------+--------+--------+
Write a SQL query to find the cancellation rate of requests made by unbanned clients between Oct 1, 2013 and Oct 3, 2013. For the above tables, your SQL query should return the following rows with the cancellation rate being rounded to two decimal places.
+------------+-------------------+
| Day | Cancellation Rate |
+------------+-------------------+
| 2013-10-01 | 0.33 |
| 2013-10-02 | 0.00 |
| 2013-10-03 | 0.50 |
+------------+-------------------+
Credits:
Special thanks to @cak1erlizhou for contributing this question, writing the problem description and adding part of the test cases.
Subscribe to see which companies asked this question
SELECT request_at AS Day,
round((max(counter) * 1.0 / count(request_at)), 2)
AS Cancellation_Rate
FROM (SELECT id,
client_id,
status,
request_at,
banned,
@counter :=
if(@curDate = request_at AND status <> 'completed',
@counter + 1,
0),
@counter :=
if(@curDate <> request_at AND status <> 'completed',
1,
@counter)
AS counter,
@curDate := request_at AS curDate
FROM (SELECT *
FROM Trips
LEFT JOIN
Users
ON Trips.client_id = Users.users_id
ORDER BY request_at) AS tmp0,
(SELECT @counter := 0, @curDate := '') AS parameters
WHERE banned <> 'Yes'
AND request_at >= '2013-10-01'
AND request_at <= '2013-10-03') AS tmp
GROUP BY request_at
SELECT Request_at DAY,
ROUND(SUM(IF(Status = 'completed', 0, 1)) / COUNT(*), 2)
'Cancellation Rate'
FROM Trips t LEFT JOIN Users t1 ON t.Client_Id = t1.Users_Id
WHERE t1.Banned = 'No' AND Request_at BETWEEN '2013-10-01' AND '2013-10-03'
GROUP BY t.Request_at;