leetcode Database3
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode Database3相关的知识,希望对你有一定的参考价值。
一、Nth Highest Salary
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
.
分析:题意为编写SQL查询获取雇员表中的第n高薪水值。例如,给定上面的雇员表,当n为2时,第n高薪水为200.如果没有第n高薪水,查询返回null。
代码:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN set N=N-1; RETURN ( # Write your mysql query statement below. SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT N,1 ); END
注意:我刚开始使用的是LIMIT N-1,1 但是will cause error,经过了解才发现
Seems like MySQL can only take numeric constants in the LIMIT syntax. Directly from MySQL documentation:
The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants (except when using prepared statements).
二、Consecutive 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.
分析:题意为编写SQL去查询所有至少连续出现3次的数字。例如,给定上面的Logs表,1是唯一至少连续出现3次的数字。
代码:
使用join就好了
# Write your MySQL query statement below SELECT DISTINCT a.Num As ConsecutiveNumbers FROM Logs a JOIN Logs b ON a.Num = b.Num JOIN Logs c ON b.Num = c.Num WHERE a.Id + 1 = b.Id AND b.Id + 1 = c.Id
# Write your MySQL query statement below SELECT DISTINCT Num FROM ( SELECT Num, COUNT(Rank) AS Cnt FROM ( SELECT Num, @curRank := @curRank + IF(@prevNum = Num, 0, 1) AS rank, @prevNum := Num FROM Logs s, (SELECT @curRank := 0) r, (SELECT @prevNum := NULL) p ORDER BY ID ASC ) t GROUP BY Rank HAVING Cnt >= 3 ) n;
此解法配合使用MySQL用户定义变量和聚组函数统计连续出现的数字个数:
以题目描述的Logs表为例,上面的SQL语句中,最内层的SELECT语句执行结果如下:
+-----+------+-----------------+ | Num | rank | @prevNum := Num | +-----+------+-----------------+ | 1 | 1 | 1 | | 1 | 1 | 1 | | 1 | 1 | 1 | | 2 | 2 | 2 | | 1 | 3 | 1 | | 2 | 4 | 2 | | 2 | 4 | 2 | +-----+------+-----------------+
执行结果中的rank列将Num转化为从1开始递增的序号,但序号只在Num出现变化时增加,(连续出现的相同数字序号也相同)
第二层SELECT语句对rank进行计数,并只保留计数不小于3的条目,执行结果为:
+-----+-----+ | Num | Cnt | +-----+-----+ | 1 | 3 | +-----+-----+
最外层SELECT语句对Num进行去重。
以上是关于leetcode Database3的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode810. 黑板异或游戏/455. 分发饼干/剑指Offer 53 - I. 在排序数组中查找数字 I/53 - II. 0~n-1中缺失的数字/54. 二叉搜索树的第k大节点(代码片段