1. 程式人生 > >LeetCode SQL刷題全解

LeetCode SQL刷題全解

1. 交換性別

Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table.

For example:
| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | m   | 2500   |
| 2  | B    | f   | 1500   |
| 3  | C    | m   | 5500   |
| 4  | D    | f   | 500    |
After running your query, the above salary table should have the following rows:
| id | name | sex | salary |
|----|------|-----|--------|
| 1  | A    | f   | 2500   |
| 2  | B    | m   | 1500   |
| 3  | C    | f   | 5500   |
| 4  | D    | m   | 500    |
Answer:
update salary 
       set sex = case sex
       when 'm' then 'f'
       else 'm'
end;

2. 不boring的電影

X city opened a new cinema, many people would like to go to this cinema. The cinema also gives out a poster indicating the movies’ ratings and descriptions.

Please write a SQL query to output movies with an odd numbered ID and a description that is not 'boring'. Order the result by rating.

For example, table 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     |
+---------+-----------+--------------+-----------+

For the example above, the output should be:
+---------+-----------+--------------+-----------+
|   id    | movie     |  description |  rating   |
+---------+-----------+--------------+-----------+
|   5     | House card|   Interesting|   9.1     |
|   1     | War       |   great 3D   |   8.9     |
+---------+-----------+--------------+-----------+

Answer:

select *
from cinema
where id%2=1 and description <> 'boring'
order by rating desc

3. Duplicate Emails

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] |
+---------+
Answer:
select Email
from Person 
group by Email
having count(*) > 1

4. Combine Two Tables

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

Answer:

select P.FirstName,P.LastName,A.City,A.State
from Person as P left join Address as A
on P.PersonId = A.PersonId

5. Employees Earning More Than Their Managers

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      |
+----------+
Answer:
select a.Name as Employee
from Employee as a inner join Employee as b
on a.ManagerId = b.Id
where a.Salary > b.Salary

6. Customers Who Never Order

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       |
+-----------+
Answer:
select Name as Customers
from Customers
where Id not in (select CustomerId from Orders)

7. Rising Temperature

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 |
+----+
Answer:
select a.Id
from Weather as a inner join Weather as b
on datediff(a.Date,b.Date) = 1 and a.Temperature > b.Temperature

8. Classes More Than 5 Students

There is a table courses with columns: student and class

Please list out all classes which have more than or equal to 5 students.

For example, the table:

+---------+------------+
| student | class      |
+---------+------------+
| A       | Math       |
| B       | English    |
| C       | Math       |
| D       | Biology    |
| E       | Math       |
| F       | Computer   |
| G       | Math       |
| H       | Math       |
| I       | Math       |
+---------+------------+

Should output:

+---------+
| class   |
+---------+
| Math    |
+---------+

Note:
The students should not be counted duplicate in each course.

Answer:
select class
from courses
group by class
having count(distinct student) >= 5

9. Delete Duplicate Emails

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]  |
+----+------------------+

Answer:

DELETE p1
FROM Person p1 inner join Person p2
on p1.Email = p2.Email AND p1.Id > p2.Id

10. Second Highest Salary

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 query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.

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

Answer:

select max(Salary) as SecondHighestSalary
from Employee
where Salary != (select max(Salary) from Employee)

11.  Rank Scores

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    |
+-------+------+

Answer:

select s1.Score,count(distinct s2.Score) as Rank
from Scores as s1 inner join Scores as s2
on s1.Score <= s2.Score
group by s1.Id
order by s1.Score desc

12. Concecutive Numbers

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.

+-----------------+
| ConsecutiveNums |
+-----------------+
| 1               |
+-----------------+

Answer:

select distinct a.Num ConsecutiveNums
from logs a, logs b, logs c
where a.Id = b.Id - 1 and b.Id = C.Id - 1 and a.Num = b.Num and b.Num = c.num

13. Department Highest Salary

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  |
+------------+----------+--------+
Answer:
select d.Name as Department,e.Name as Employee, e.Salary 
from Employee as e inner join Department as d
on e.DepartmentId = d.Id
where (e.DepartmentId,e.salary) in (select DepartmentId,max(Salary) from Employee group by DepartmentId)






相關推薦

LeetCode SQL

1. 交換性別 Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all

第四天(41道)

rom blog str case 循環 clas 同名 http name 41道題: 重要的 連表查詢 分組 制表語句: 班級表 Table: class Create Table: CREATE TABLE

[LeetCode][Python]記錄 1. 兩數之和

ron 題記 細節 重復 給定 假設 利用 tar 分享圖片 第一次做發現很多小細節以前都沒註意過,感覺還是蠻頭疼的。 題目: 給定一個整數數組和一個目標值,找出數組中和為目標值的兩個數。 你可以假設每個輸入只對應一種答案,且同樣的元素不能被重復利用。 根據題目要求

leetCode 1號, 兩數之和的key , python3三種方法實現

原題如下 給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。 你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。 示例: 給定 nums = [2, 7, 11, 15], target = 9 因為 nums[0] + nums[1] = 2 + 7 = 9 所以

LeetCode 第47 排列2

  (一)  題目描述 給定一個可包含重複數字的序列,返回所有不重複的全排列示例:輸入:[1,1,2]輸出:[[1,1,2][1,2,1][2,1,1]](二)解題演算法 先對給定的序列nums進行排序,使得大小相同的元素排在一起. 新建一個used陣列,大小與nums相同,

leetcode 110筆記——dfs——平衡二叉樹判斷問題

  在這道題中,我整整是做了一天的時間來完成它,首先我先了解了什麼事平衡二叉樹,複習了一遍二叉樹的相關知識,也算是鞏固吧,這道題中我用了整整兩邊遞迴,一個遞迴是求樹的高度,一個是判斷樹是否為平衡二叉樹,在這個題中為了更好的瞭解遞迴,可以把遞迴看做成一個黑盒子,不必細瞭解其內部的呼

The Python Challenge 謎(持續更新)

Python Challenge(0-2) The Python Challengehttp://www.pythonchallenge.com/ 是個很有意思的網站,可以磨練使用python的技巧,每一關都有挑戰,要編寫相應的程式碼算出關鍵詞,才可以獲取下一關的url,還是很好玩的QAQ LEVE

leetcode easy心得

持續更新 67.二進位制求和 給定兩個二進位制,返回他們的和。輸入為非空字串並且只包含1和0. class Solution { public String addBinary(String a, String b) { StringBuilder result = new

LeetCode-Easy(32) Linked List Cycle

Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using extra space? 給定一個連結串列,確定它是否有一個迴圈

LeetCode-Easy(31) Single Number

Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have a li

LeetCode-Easy(30) Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximu

LeetCode-Easy(29) Best Time to Buy and Sell Stock

Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete

LeetCode-Easy(28) Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3,3,1]. N

LeetCode-Easy(27) Pascal's Triangle

Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, Return [ [1]

LeetCode-Easy(26) Path Sum

Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given

LeetCode-Easy(25) Minimum Depth of Binary Tree

Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the

LeetCode-Easy(24) Balanced Binary Tree

Given a binary tree, determine if it is height-balanced. For this pro

LeetCode-Easy(23) Convert Sorted Array to Binary Search Tree

Given an array where elements are sorted in ascending order, convert it to a height balanced BST. 將有序陣列轉化為二分查詢樹

LeetCode-Easy(33) Min Stack

Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. push(x) -- Push element x onto stack. pop()

leetcode(python & java)解析:【兩數之和】 重點【Hash】

題目描述 給定一個整數陣列和一個目標值,找出陣列中和為目標值的兩個數。 你可以假設每個輸入只對應一種答案,且同樣的元素不能被重複利用。 Given an array of integers, return indices of the two numbers s