leetcode database题目

Posted winters1992

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode database题目相关的知识,希望对你有一定的参考价值。

LeetCode有10道SQL的题目,最近学习SQL语言,顺便刷题强化一下,

说实话刷完SQL学习指南这本书,不是很难,上面的例子 跟语法规则我都能理解透,

实际中来做一些比较难的业务逻辑题,却一下子很难想起如何利用SQL来描述

还是要多刷题开阔自己的思路,把学到手的语法加以练习 应用到实际中去

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

这个题目题意是要求找到比前一天气温高的条目
# Write your mysql query statement below
select Id from Weather w1 where Temperature >(select Temperature from Weather w2 where to_days(w2.Date)=(to_days(w1.Date)-1))

这里用了子查询,针对外部查询的每一条记录,在子查询中找到前一天的气温 作为子查询的结果 最后与外部查询相比较,这样就能找出结果来

当然这里思路比较简单,我想出来的都是最简单 也是最容易理解的方案。

 

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.

找出有完全一样email的条目,

 

解题的思路在于group by 通过集聚函数count计算条目,当条目大于2则显示,当然这里不能使用where 因为在SQL里面where必须在group by之前,然后才能集聚

所以此处只能使用having来完成 group by集聚完成之后的任务

select Email from Person group by Email having count(*)>=2

 

181. Employees Earning More Than Their Managers

找出比他们经理还挣得多的员工

毫无疑问子查询duang起

select Name Employee from Employee a where Salary >(select Salary from Employee where Id=a.ManagerId)

 

175. Combine Two Tables

这题直接外连,不用讲思路了

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

 

以上是关于leetcode database题目的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode:Task Scheduler分析和实现

解决spring-boot启动中碰到的问题:Cannot determine embedded database driver class for database type NONE(转)(代码片段

leetcode_1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold_[二维前缀和](代码片段

java.lang.NullPointerException: Attempt to invoke virtual method ‘int android.database.sqlite异常(代码片段

LEETCODE 003 找出一个字符串中最长的无重复片段

LeetCode:Database 61.市场分析 II