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?

MySQLの`GROUP BY`句の使い方

Posted at

はじめに

MySQLのGROUP BY句は、SQLで集計関数と共に使用され、結果セットを一つ以上の列でグループ化するために使用されます。これにより、各グループごとに集計関数(例えばSUMCOUNTAVGなど)が適用され、グループごとの集計結果が得られます。

GROUP BY句の基本構文

SELECT
    column1,
    column2,
    aggregate_function(column3)
FROM
    table_name
GROUP BY
    column1,
    column2;
  • column1, column2: グループ化する列です。
  • aggregate_function(column3): 集計関数です。例としてSUM(column3)COUNT(column3)などがあります。

具体例

例1: 基本的な使用方法

テーブルsalesに以下のデータがあるとします。

id product quantity price
1 A 10 100
2 B 20 200
3 A 30 150
4 B 10 250
5 A 20 100

各製品ごとの総売上金額を計算するクエリは以下の通りです。

SELECT
    product,
    SUM(quantity * price) AS total_sales
FROM
    sales
GROUP BY
    product;

このクエリは、製品ごとにグループ化し、各製品の総売上金額を計算します。

結果

product total_sales
A 6500
B 7000

例2: 複数の列でグループ化

テーブルordersに以下のデータがあるとします。

id customer product quantity
1 Alice A 10
2 Bob B 20
3 Alice A 5
4 Bob A 15
5 Alice B 10

顧客ごと、製品ごとの合計数量を計算するクエリは以下の通りです。

SELECT
    customer,
    product,
    SUM(quantity) AS total_quantity
FROM
    orders
GROUP BY
    customer,
    product;

このクエリは、顧客ごと、製品ごとにグループ化し、それぞれの合計数量を計算します。

結果

customer product total_quantity
Alice A 15
Alice B 10
Bob A 15
Bob B 20

GROUP BY句のポイント

  1. グループ化の基準:

    • GROUP BY句に指定された列を基準に結果セットがグループ化されます。これにより、各グループに対して集計関数が適用されます。
  2. SELECT句の制約:

    • GROUP BY句を使用する場合、SELECT句に含めることができる列は、GROUP BY句で指定された列か、集計関数を適用した列に限られます。
  3. 集計関数の使用:

    • SUMCOUNTAVGMINMAXなどの集計関数を使用して、グループごとの集計結果を計算します。
  4. HAVING句の使用:

    • HAVING句を使用して、グループ化された結果に対してフィルタを適用できます。HAVING句は、GROUP BY句の後に続き、集計結果に条件を適用するために使用されます。

例3: HAVING句の使用

前述のordersテーブルに対して、合計数量が20以上のグループを取得するクエリは以下の通りです。

SELECT
    customer,
    product,
    SUM(quantity) AS total_quantity
FROM
    orders
GROUP BY
    customer,
    product
HAVING
    SUM(quantity) >= 20;

結果

customer product total_quantity
Bob B 20

このクエリは、顧客ごと、製品ごとの合計数量を計算し、合計数量が20以上のグループのみを結果として返します。

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?