LoginSignup
4
4

More than 5 years have passed since last update.

みんなの為のMySQLまとめ(9)

Posted at

参考
http://homepage2.nifty.com/sak/w_sak3/doc/sysbrd/mysql_12.htm

■集計問い合わせ(合計値)

・集計問い合わせを行うには、group by 句を使用する。
この例では、key1 の先頭が「a」で始まる明細を key1 単位に集計(サマリー)
し、data1 の合計が 10 以上のものを問い合わせる。
having 句は、集計後の結果に対して抽出条件が指定できる。

select key1, sum(data1) from testm
where key1 like 'a%'
group by key1
having sum(data1) >= 10
;

・count() を使用すると、合計件数が問い合わせられる。
(問い合わせ件数表示、照会件数表示、抽出件数)
この例では、key1 単位に集計し、data1 の合計が 10 以上のものを
問い合わせる。

select key1, count(*), sum(data1) from testm
group by key1
;
kobito.1423449846.106480.png

・単純に特定の明細のレコード件数を問い合わせるときは、次のように使用す
る。この例では、key1 の先頭が「a」で始まる明細の件数が得られる。

select count(*) from testm
where key1 like 'a%'
;
kobito.1423579043.718863.png

・max、min を使用すると最大値と最長値を問い合わせることができる。
この例では、key1 毎の data1 の最大と最小が得られる。

select key1, max(data1), min(data1) from testm
group by key1
;
kobito.1423673538.223021.png

・testm のキーがユニークでないと仮定すると、同じキーのレコードが複数
存在する事になる。
distinct を指定すると重複レコードを取り除いて問い合わせできる。
distinct の代わりに unique と Oracle のように指定することはできない。
(重複データ)

select distinct key1
from testm
;
kobito.1423673734.695547.png

・union all を使用すると問い合わせ結果をマージできる。
union all の代わりに union とだけ指定すると、重複レコード
は含まれない。(表を合わせ、付け足す)

select * from testm
where key1 like 'a%'
union
select * from testm
where key1 like 'a%'
;
kobito.1423674236.103380.png

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