0
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でcaseを使う

Last updated at Posted at 2021-05-04

caseを使ってみよう

ユーザ情報テーブルと、購入履歴テーブルを結合し、
購入回数ごとにランキングを付ける。

5回以上 ランクA
2回以上 ランクB
1回未満 ランクC

select users.id,count(*),
case
when count(*) >= 5 then 'A'
when count(*) >= 2 then 'B'
else 'C'
end as user_rank
from users
join orders
on users.id = orders.user_id
group by users.id;
  • end は必須! ★忘れやすいので注意★
  • as でカラム名を付ける

#nullの値を0にしてみよう

select products.id,products.name,
case
when sum(order_details.product_qty) is null
then 0
else sum(order_details.product_qty)
end as num
from products
left outer join
order_details
on products.id = order_details.product_id
group by products.id

left join を使うとnullになることがあり、nullだと都合が悪いときに0を入れておく。

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