「SQLite3」avg関数で指定カラムの値の平均を取得する

環境
Windows 10 Home 64bit
sqlite 3.37

書式
avg(カラム名)
引数に指定したカラムに含まれている値の中で NULL 以外の値の平均を返します。
対象のカラムの値が NULL だけだった場合は、 avg 関数は NULL を返します。

使用例
1.テーブルを作成します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sqlite> create table infotbl(tname text, score integer, memo text);
sqlite> create table infotbl(tname text, score integer, memo text);
sqlite> create table infotbl(tname text, score integer, memo text);

2.insert文でテーブルにデータを挿入します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sqlite> insert into infotbl values('Chang', 82, 'u001');
sqlite> insert into infotbl values('Fa', 76, 'm002');
sqlite> insert into infotbl values('Tun', 68, 'n003');
sqlite> insert into infotbl values('Tun', 92, 'n003');
sqlite> insert into infotbl values('Chang', 82, 'u001'); sqlite> insert into infotbl values('Fa', 76, 'm002'); sqlite> insert into infotbl values('Tun', 68, 'n003'); sqlite> insert into infotbl values('Tun', 92, 'n003');
sqlite> insert into infotbl values('Chang', 82, 'u001');
sqlite> insert into infotbl values('Fa', 76, 'm002');
sqlite> insert into infotbl values('Tun', 68, 'n003');
sqlite> insert into infotbl values('Tun', 92, 'n003');

3.avg関数を使ってscoreカラムの値の平均を取得します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sqlite> select avg(score) from infotbl;
79.5
sqlite> select avg(score) from infotbl; 79.5
sqlite> select avg(score) from infotbl;
79.5

4.memoカラム毎にグループ化して行数を取得します

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
sqlite> select memo, avg(score) from infotbl group by memo;
m002,76.0
n003,80.0
u001,82.0
sqlite> select memo, avg(score) from infotbl group by memo; m002,76.0 n003,80.0 u001,82.0
sqlite> select memo, avg(score) from infotbl group by memo;
m002,76.0
n003,80.0
u001,82.0

 

SQLite

Posted by arkgame