1
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?

【SQL】SELECTをする際、特定条件時に既存の値に「-(マイナス)」を入れる

Last updated at Posted at 2024-03-26

結論

SELECT
    hoge,  /*1かどうかの確認用、fugaだけ欲しければ不要*/
    CASE WHEN hoge = '1'
        THEN -1 * fuga
        ELSE fuga
    END AS fuga
FROM test_table
;

何をしているのか

test_table内の項目「hoge」が'1'の時、
同テーブル内の項目「fuga」の値に「-1」を掛ける(*で掛ける)ことで先頭に「-」を付ける。

実際の動き

既存のtest_tableの中身

hoge fuga
1 1100
0 1000

結論のSELECTを実行

hoge fuga
1 -1100
0 1000

「fuga」がテーブル定義上、テーブル定義の最大桁を超過しても「-」は付く。
(最大桁が「4」であっても上記の実際の動きのように「-」が付く)

1
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
1
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?