Leetcode 177. Nth Highest Salary

原创 2016年08月31日 05:15:46

177. Nth Highest Salary

Total Accepted: 10762 Total Submissions: 66455 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.

思路:

这个题可以沿用上题的思路,并且不需要重新命名列名称。需要注意的地方就是limit函数只支持一个数,不支持表达式,比如N-1。上一道题是2th, 代码是limit 1,1。这题把第一个1换成N-1就行了,但是因为不支持表达式,需要先赋值N = N-1。为了方便读者,上一题的说明依然附在了文章结尾。

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

在我们使用查询语句的时候,经常要返回前几条或者中间某几行数据,这个时候怎么办呢?不用担心,mysql已经为我们提供了这样一个功能。
SELECT * FROM table  LIMIT [offset,] rows | rows OFFSET offset

LIMIT 子句可以被用于强制 SELECT 语句返回指定的记录数。LIMIT 接受一个或两个数字参数。参数必须是一个整数常量。如果给定两个参数,第一个参数指定第一个返回记录行的偏移量,第二个参数指定返回记录行的最大数目。初始记录行的偏移量是 0(而不是 1): 为了与 PostgreSQL 兼容,MySQL 也支持句法: LIMIT # OFFSET #。 

mysql> SELECT * FROM table LIMIT 5,10;  // 检索记录行 6-15

//为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1: 
mysql> SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.

//如果只给定一个参数,它表示返回最大的记录行数目: 
mysql> SELECT * FROM table LIMIT 5;     //检索前 5 个记录行

//换句话说,LIMIT n 等价于 LIMIT 0,n。


版权声明:本文为博主原创文章,未经博主允许不得转载。

相关文章推荐

Nth Highest Salary 解法讨论(Mysql)

题目分析 Write a SQL query to get the nth highest salary mysql join order by limit offset

LeetCode | Second Highest Salary & Nth highest salary

Write a SQL query to get the second highest salary from the Employee table. +----+--------+ | Id | S...

LeetCode Second Highest Salary

Write a SQL query to get the second highest salary from the Employee table. +----+--------+ | Id | S...

Leetcode 176. Second Highest Salary

176. Second Highest Salary Total Accepted: 22494 Total Submissions: 100791 Difficulty: Easy Writ...

MySQL-Second Highest Salary

Write a SQL query to get the second highest salary from the Employee table. +----+--------+ | Id | S...

Second Highest Salary

Write a SQL query to get the second highest salary from the Employee table. +-

184. Department Highest Salary

The Employee table holds all employees. Every employee has an Id, a salary, and there is also a colu...

题目8:MySQL---------Department Highest Salary

The Employee table holds all employees. Every employee has an Id, a salary, and there is also a col...

【LeetCode-面试算法经典-Java实现】【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】

【019-Remove Nth Node From End of List(移除单链表的倒数第N个节点)】【LeetCode-面试算法经典-Java实现】【所有题目目录索引】原题  Given a l...

《leetCode》:Remove Nth Node From End of List

题目描述Given a linked list, remove the nth node from the end of list and return its head.For example, ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Leetcode 177. Nth Highest Salary
举报原因:
原因补充:

(最多只允许输入30个字)