1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【メモ】SQL 2番目に大きい/小さい値を取得する

Posted at

SQLを用いて「2番目に大きい値を取得しよ」との問題に一瞬戸惑ったので自分用にメモ。
(問題はLeetCodeより https://leetcode.com/problems/second-highest-salary/description/?envType=study-plan-v2&envId=top-sql-50)

Q1. 下記のテーブルから2番目に高い給与(salary)を取得し、カラム名はSecondHighestSalaryとせよ。

+----+--------+
| id | salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+

2番目に大きい(もしくは小さい)値を取得するのにいくつか方法があったので記します。

  • 方法1
SELECT MAX(salary) AS SecondHighestSalary
FROM Employee
WHERE salary < (SELECT MAX(SALARY) FROM Employee);
  • 方法2
SELECT 
(SELECT DISTINCT Salary
FROM Employee order by salary desc
limit 1 offset 1)
AS SecondHighestSalary;
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?