当前位置:网站首页>Solutions to ten questions of leetcode database
Solutions to ten questions of leetcode database
2022-07-25 08:41:00 【Four fires】
stay Before doing algorithm problems Found on the way ,LeetCode The database solution is introduced above , There are ten questions , So I did it in these two nights . The answer is secondary, and the main benefit is , Just review SQL How to write some query statements , Such as custom variables and common functions . The topics are relatively simple , Explain less , Mainly post questions and answers .
# | Title | Acceptance | Difficulty | |
|---|---|---|---|---|
175 | Combine Two Tables | 32.5% | Easy | |
176 | Second Highest Salary | 23.8% | Easy | |
177 | Nth Highest Salary | 14.1% | Medium | |
178 | Rank Scores | 20.7% | Medium | |
180 | Consecutive Numbers | 20.2% | Medium | |
181 | Employees Earning More Than Their Managers | 44.2% | Easy | |
182 | Duplicate Emails | 38.0% | Easy | |
183 | Customers Who Never Order | 34.2% | Easy | |
184 | Department Highest Salary | 19.2% | Medium | |
185 | Department Top Three Salaries | 16.3% | Hard |
Combine Two Tables
【 subject 】
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 p left outer join Address a on p.PersonId=a.PersonId;Second Highest Salary
【 subject 】
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.
【 answer 】 The title is simple. , But if it's like me , I found that I don't remember several commonly used functions , You can review .
select IFNULL( (select e.Salary from Employee e group by e.Salary order by e.Salary desc limit 1, 1), NULL) SecondHighestSalary;Nth Highest Salary
【 subject 】
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.
【 answer 】 The first n high , You have to use custom variables , I seldom use this thing , So I reviewed it first .
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
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
);
ENDRank Scores
【 subject 】
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 】 Another topic of custom variables , This pattern should be familiar , It's quite common . If you can't use “set @var_name=0;” Words ( Ask for one sentence SQL Get it done ), That can be defined in the clause “select @var_name:=0”, Then use this variable outside it .
select s.Score, t.Rank from (
select @row_num:[email protected]_num+1 Rank, Score from (
select Score from Scores group by Score desc
) t1 join (
select @row_num := 0 from dual
) t2
) t, Scores s where s.Score=t.Score group by Score desc, Rank asc, Id;Consecutive Numbers
【 subject 】
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.
【 answer 】
select DISTINCT(l1.Num) from Logs l1, Logs l2, Logs l3 where l1.Id+1=l2.Id and l1.Id+2=l3.Id and l1.Num=l2.Num and l1.Num=l3.Num;Employees Earning More Than Their Managers
【 subject 】
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 e.Name from Employee e, Employee m where e.ManagerId=m.Id and e.Salary>m.Salary;Duplicate Emails
【 subject 】
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.
【 answer 】
select distinct(p.Email) from Person p, Person q where p.Id!=q.Id and p.Email=q.Email;Customers Who Never Order
【 subject 】
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 c.Name Customers from Customers c where c.Id not in (
select CustomerId from Orders
)Department Highest Salary
【 subject 】
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 Department, e.Name Employee, s.Salary from (
select MAX(e.Salary) Salary, e.DepartmentId from Employee e, Department d where e.DepartmentId=d.Id group by e.DepartmentId
) s, Employee e, Department d where s.Salary=e.Salary and e.DepartmentId=d.Id and e.DepartmentId=s.DepartmentId;Department Top Three Salaries
【 subject 】
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 |
+------------+----------+--------+【 answer 】 Take this question MySql It's actually a little difficult , If I use Oracle, I can rank() over(partition by xxx order by xxx desc) This is what happened , however MySql The frustration is that there is no such partition operation . But in the end, it was done with the help of three user-defined variables . The meaning is not explained , It's easy to understand :
select Department, Employee, Salary from (
select
IF(@lastDep!=t1.Department, @count:=0, @count:[email protected]), IF(@lastDep=t1.Department and @lastSalary!=t1.Salary, @count:[email protected]+1, @count:[email protected]) Cnt,
@lastDep:=t1.Department, @lastSalary:=t1.Salary,
t1.Department, t1.Employee, t1.Salary
from (
select d.Name Department, e.Name Employee, e.Salary
from Department d, Employee e where d.Id=e.DepartmentId order by Department asc, Salary desc
) t1, (
select @lastDep:=null, @lastSalary:=0, @count:=0 from dual
) t2
) f where Cnt<3;After the event , I went to the discussion area , Find a beautiful answer , There are no custom variables , The key is distinct(Salary) Go to Heyuan Salary Compare , Filter out that the number of occurrences under this condition is greater than 3 The situation of :
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) in (0, 1, 2)
and
E.DepartmentId = D.Id
order by E.DepartmentId, E.Salary DESC;The articles are all original without special indication , It shall not be used for any commercial purpose without permission , Please keep the integrity of reprint and indicate the source link 《 Four fire's nagging 》
边栏推荐
- Tips for improving code sustainability, take connectto method as an example.
- 公寓报修系统(IDEA,SSM,MySQL)
- When testing VPN, the IP found by the command line is inconsistent with that of Baidu search
- Hash table questions (Part 1)
- 游戏外挂怎么做?
- Centernet network structure construction
- Redis最佳实践
- Dirty data and memory leakage of ThreadLocal
- 本周大新闻|FCC曝光Pico 4 VR一体机,雷朋母公司建立智能眼镜实验室
- C#入门系列(三十) -- 异常处理
猜你喜欢

Blue and white porcelain used by Charles

Initial knowledge of WebService (generate jar packages and call methods in remote services)

Graduation project of wechat small program ordering system of small program completion works (4) opening report

How to set up a personal website for free

Idea2021 failed to start. Could not find main class com/intellij/idea/main

The database of idea cannot prompt the table name, field name, and schema cannot be loaded

Foundation 31: Selenium positioning dynamic ID element

Network solutions for Alibaba cloud services

【黑马程序员】Redis学习笔记003:Redis事务

JS pop up picture Lightbox light box plug-in spotlight.js
随机推荐
Idea failed to start the project yamlexception Chinese file encoding format
OpenGL es to realize the visualization of real-time audio
SSM+JSP+MYSQL实现的宠物领养收养管理系统源码
Efcore's solution of multi tenant zero script, table and database read-write separation under SaaS system
递归调用实现打印一个整数的每一位
Svg creative underline style JS special effect
Nuscenes dataset 3D mot demo, end-to-end target detection and tracking, joint detection and tracking framework
When testing VPN, the IP found by the command line is inconsistent with that of Baidu search
When crontab scheduled task executes jar through script, it encounters a pit where jar package execution is invalid
Foundation 32: page element positioning method XPath --- axis positioning method
@The difference and use of value and configurationproperties
Huawei device remote login (Telnet, SSH) configuration
华为设备远程登录(Telnet、SSH)配置
C # introductory series (30) -- exception handling
Wechat Reservation Reservation of applet completion works applet graduation project (8) graduation project thesis template
How to set up a personal website for free
孙子兵法随感
PHP reports an error: classes\phpexcel\cell php Line(594) Invalid cell coordinate ESIGN1
【万字长文】使用 LSM-Tree 思想基于.Net 6.0 C# 实现 KV 数据库(案例版)
【黑马程序员】Redis学习笔记005:企业级解决方案