学生向けプログラミング入門 | 無料

学生向けにプログラミングを無料で解説。Java、C++、Ruby、PHP、データベース、Ruby on Rails, Python, Django

データベース| HSQLDB | 05 | 関数 count() avg() max()

<<前  [TOP]  次>>


今まではselectの出力をそのまま表示してきましたが、例えば「'国語'という言葉を含む書名の本はいくつあるか?」という問にはどう答えたらいいでしょうか?
こうした時SQLでは次の例のように関数count()を使用することが出来ます。


【例1:「国語」という言葉を含む本の数】

select count(title) from books where title like '%国語%';



「select count(title) from books where title like &#x27;%国語%&#x27;;」
「select count(title) from books where title like '%国語%';」


ここで関数count()は「select title from books where title like '%国語%';」が検索した行の数(書名の数)を返すことになります。


次の例では「count()」の形で、テーブルの全行数がカウントされています。


【例2:テーブル「books」の行数を数える】

select count(*) from books;



「select count(*) from books;」
「select count(*) from books;」


次の例を見てください。
この例では「count( distinct 項目名 )」という形で項目の相互にあい異なる値の数が数えられます。
selectの結果に同じ値の出力が含まれていてもdistinct が項目名についていれば、重複した出力は省かれるのと同じです。


【例3:「国語」という言葉を含む本を出版している出版社の数】

select count(distinct publisher) from books where title like '%国語%';



「select count(distinct publisher) from books where title like &#x27;%国語%&#x27;;」
「select count(distinct publisher) from books where title like '%国語%';」


次の例は書名に「国語」が付く本の平均価格を求めるものです。


【例4:書名に「国語」が付く本の平均価格】

select avg(price) from books2 where title like '%国語%';



「select avg(price) from books2 where title like &#x27;%国語%&#x27;;」
「select avg(price) from books2 where title like '%国語%';」


次の例は書名に「国語」が付く本の最大価格を求めるものです。


【例5:書名に「国語」が付く本の最大価格】

select max(price) from books2 where title like '%国語%';



「select max(price) from books2 where title like &#x27;%国語%&#x27;;」
「select max(price) from books2 where title like '%国語%';」


↓↓クリックして頂けると励みになります。


<<前  [TOP]  次>>