0
0

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のCASE式を用いて複数列の最大値を求める

Posted at

問題

Greatestsという仮のテーブルがあるとします。

複数列の中から、最大を選び

key x y z
A 1 2 3
B 5 5 2
C 4 7 1
D 3 3 8

以下のような出力結果になるような SQLを書いてください。
まずは、xとy 列の2列の比較でやりましょう。

key greatest
A 2
B 5
C 7
D 3

解き方の方針

CASE式の条件をx>yとかにすればすぐできます。

SQL

SELECT
	key,
	CASE WHEN x > y THEN x
	END y AS greatest
FROM Greatests

問題

では、比較対象をx,y,zの3列にしたらどうでしょうか?

解き方の方針

CASE式の中でCASE式を入れて比較すればOKです

SQL

SELECT
	key,
	CASE WHEN
                          CASE WHEN x > y THEN x ELSE y END < z
                THEN z
                ELSE
             CASE WHEN x > y THEN x ELSE y END
	END AS greatest
FROM Greatests

CASE WHEN x > y THEN x ELSE y END」というCASE式をCASE式の中に書くことで実現できます。

こんなことができるのも、CASE式の実行値が値だからこそです。

同じ容量で、列は増やせますが、可読性は落ちます。

参照

23p

アウトプット100本ノック実施中

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?