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 3 years have passed since last update.

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

Last updated at Posted at 2019-12-11

#2番目に大きい値を取得したい
意外とめんどくさいので簡単にまとめてみました。
適当に作った一時データの2番目に大きい値を取得します。
サンプルコードはそのまま実行できるようにしてあるので、試してみてください

##値のみを取得したい場合

main.sql
DROP TABLE IF EXISTS #tes

SELECT 1 AS id, 11 AS num, 'Adam'    AS cust_name INTO #tes UNION ALL
SELECT 3 AS id, 12 AS num, 'Bob'     AS cust_name           UNION ALL
SELECT 5 AS id, 13 AS num, 'Charlie' AS cust_name           UNION ALL
SELECT 7 AS id, 14 AS num, 'Dom'     AS cust_name           UNION ALL
SELECT 8 AS id, 15 AS num, 'Eva'     AS cust_name           UNION ALL
SELECT 9 AS id, 16 AS num, 'Flynn'   AS cust_name 


--プランA その値だけ持ってくる
SELECT MAX(id) AS 二番目
FROM #tes AS MAIN
CROSS JOIN (SELECT MAX(id) AS 最大 from #tes) AS F
WHERE id <> 最大

SELECT MAX(id) AS 二番目
FROM #tes
WHERE id < (SELECT MAX(id) FROM #tes)

このままDECLAREで定義した変数などに入れることができます。
CROSS JOINするのでデータ量が多くなるほど遅くなります。
WHEREのほうに入れるのが一番使い勝手がいいかもしれません。

##レコードを取得したい場合

main.sql
DROP TABLE IF EXISTS #tes

SELECT 1 AS id, 11 AS num, 'Adam'    AS cust_name INTO #tes UNION ALL
SELECT 3 AS id, 12 AS num, 'Bob'     AS cust_name           UNION ALL
SELECT 5 AS id, 13 AS num, 'Charlie' AS cust_name           UNION ALL
SELECT 7 AS id, 14 AS num, 'Dom'     AS cust_name           UNION ALL
SELECT 8 AS id, 15 AS num, 'Eva'     AS cust_name           UNION ALL
SELECT 9 AS id, 16 AS num, 'Flynn'   AS cust_name 


--プランB そのレコードを取得する①
SELECT * 
FROM (SELECT ROW_NUMBER() OVER(ORDER BY id DESC) AS RNUM
           , *
	  FROM #tes
	 ) AS A
WHERE RNUM = 2

ROW_NUMBERは直接WHEREで指定できないので入れ子にして対応します。
見た目が少し回りくどい気がするのと、ROW_NUMBERを付与するのに意外と時間がかかるので、大量のデータだとやはり遅いです。

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?