4
3

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 1 year has passed since last update.

【SQL】WITH句を覚えた #備忘録

Last updated at Posted at 2022-07-26

これはなに

SQLのWITH句を覚えたのでメモを残す

筆者

  • 非エンジニア(マーケティング職)
  • SQLをお勉強中

WITH句とはなんぞや

SQL文内で新たにテーブルを作り、名前を付けることが出来る句のこと。

WITH句で呼び出したテーブルのことをCTE(共通テーブル式)と言うらしい。
WITH句を使って再帰呼び出しすることを再帰WITH句と言ったり、
呼び出したテーブルを再帰共通表式(テーブル)と言ったりするらしいです。

WITH句の書き方

with
    '作成するテーブル名'
AS
    (
    '作成するテーブルを作るクエリ'
    )

使用例

やりたいこと

  • 商品購入数が多いユーザー上位3名のメールアドレスを抽出する

テーブル

テーブル①:purchase

purchase_id user_id quantity
1 1 1
2 1 1
3 3 5
4 2 2
5 2 1
6 4 1
7 3 1
8 5 2
9 1 3
10 6 1

テーブル②:user

user_id email
1 cham.hoge@gmail.com
2 cham.test@gmail.com
3 cham.qiita@gmail.com
4 chamcham.qiita@gmail.com
5 cham.hogehoge@gmail.com

WITH句を使ったクエリ


WITH 
    puchase_quantity_top3_users 
AS (
    SELECT
        purchase_id
        sum(quantity)
    FROM
        purchase
    GROUP BY 1
    ORDER BY 2 DESC
    LIMIT 3
    ),

SELECT
    email
FROM
    user
JOIN
    puchase_quantity_top3_users
ON
    user.user_id=puchase_quantity_top3_users.user_id;

出力結果

email
cham.qiita@gmail.com
cham.hoge@gmail.com
cham.test@gmail.com

メモ

  • WITH句で定義したテーブルは何度も使える
  • JOIN句でサブクエリ書くより読みやすい
4
3
2

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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?