レコードの値の平均値を求める - SQL

レコードの値の平均値を求めるSQLを紹介します。

書式

select AVG((平均値を求める列名)) from (テーブル名)
の書式でAVG関数を呼び出します。

特定の条件に一致するレコードの平均を求める場合は
select AVG((平均値を求める列名)) from (テーブル名) where (条件式)
特定の列でグループにまとめて集計する場合は
select AVG((平均値を求める列名)) from (テーブル名) group by (列名)
とします。

例1:テーブルのすべてのレコードの平均値を取得する

products テーブル
idnamepricecategory
1Penguin250Bird
2Bear1050Mammal
3Duck150Bird
4Camel550Mammal
5Owl185Bird
6Whale880Mammal

上記のテーブルで"price"の平均を求める場合は以下のSQLを実行します。
select AVG(price) from products 
結果
結果は以下となります。
(列名なし)
510.833333

補足

列名を付ける場合のSQLは以下になります。
select AVG(price) as average from products 
select agerage=AVG(price) from products 
結果
結果は以下となります。
average
510.833333

例2:条件に一致したレコードの平均値を取得する

products テーブル
idnamepricecategory
1Penguin250Bird
2Bear1050Mammal
3Duck150Bird
4Camel550Mammal
5Owl185Bird
6Whale880Mammal

上記のテーブルでcategoryが"Mammal"の平均を求める場合は以下のSQLを実行します。
select AVG(price) from products where category='Mammal'
結果
結果は以下となります。
(列名なし)
826.666666

補足

列名を付ける場合のSQLは以下になります。
select AVG(price) as average from products where category='Mammal'
または
select agerage=AVG(price) from products where category='Mammal'
結果
結果は以下となります。
average
826.666666

例3:group by を用いる場合

group by を用いると指定した列ごとのグループにまとめて、集計することができます。
products テーブル
idnamepricecategory
1Penguin250Bird
2Bear1050Mammal
3Duck150Bird
4Camel550Mammal
5Owl185Bird
6Whale880Mammal

上記のテーブルでcategoryごとの平均を求める場合は以下のSQLを実行します。
select category,AVG(price) as average from products group by category
結果
結果は以下となります。
categoryaverage
Bird195.000000
Mammal826.666666

このページのキーワード
  • レコードの値の平均値を取得する
著者
iPentec.com の代表。ハードウェア、サーバー投資、管理などを担当。
Office 365やデータベースの記事なども担当。
最終更新日: 2020-05-19
作成日: 2014-07-22
iPentec all rights reserverd.