2
2

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

SQLのCASE文

Posted at

今回はSQLのCASE文について説明します。
というか、自分がすぐCASE文の使い方を忘れてしまうので自分用メモなんですが……。

まずは、もっとも単純なCASE文を書いてみます。
jobカラムには職業がコードで登録されているため、名称を紐づけているSQLです。

CASE
    WHEN job = 0 THEN '会社員'
    WHEN job = 1 THEN '自営業'
    ELSE '不明'
END

ちなみに、CASE文の中では不等号やIN句も使用できます。

CASE
    WHEN age < 20 THEN '子供'
    WHEN age >= 20 THEN '大人'
END
CASE
    WHEN kbn IN (0, 1, 2) THEN '分類1'
    WHEN kbn IN (3, 4) THEN '分類2'
    ELSE '分類3'
END

もちろん、複数条件を指定することもできます。

CASE
    WHEN rank = 0 AND score >= 80 THEN '評価S'
    WHEN rank = 1 AND score >= 80 THEN '評価A'
    ELSE '評価B'
END
2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?