ねこきっくぱんちのメモ帳

ITに関することいろいろめも。たまにアニメ。

MySQL007 様々な条件で抽出(2)

chap8 続き

■複数条件を指定した選択(AND/OR)
・AND
select * from chap8 where uria>=50 and uria<= 100;
select * from chap8 where bang like '%1' and tuki=4;

・OR
select * from chap8 where uria<50 or uria>200;

・複合
select * from chap8 where bang like '%1' and tuki=4 or uria>=200;
select * from chap8 where (uria>200 or bang like '%1') and tuki=4;
※ANDとORが混ざっている時は、ANDが優先される ★注意
AorB and Cの場合は、(AorB) and Cと()でくくる。



■CASE WHEN
条件によって入力する値を変化させる場合

select bang,uria,
case
when uria>200 then '多い!!!'
when uria>=50 then '普通'
else '少ない...'
end as '評価'
from chap8;


★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

SQLの実行順序
FROM → WHERE → GROUPBY → HAVING → SELECT → ORDERBY

a.抽出してからのグループ化(where->groupBy)
select bang,avg(uria) from chap8 where uria>=50 group by bang;

b.グループ化してから並べる(groupBy->having)
select bang,avg(uria) from chap8 group by bang order by avg(uria) desc;
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★

■並び替え(ORDER BY asc/desc, limit/offset, GROUP BY)
・昇順
select * from chap8 order by uria; //デフォルトはasc;
select * from chap8 order by uria asc;

・降順
select * from chap8 order by uria desc;
select * from chap8 order by uria desc limit 5;

・範囲指定(OFFSET)
select * from chap8 order by uria desc limit 2 offset 3;

■グループごとに表示
select * from chap8 group by bang;
select count(*) from chap8 group by bang;

select
bang,count(*) as '件数'
from chap8
group by bang;

・グループごとの合計・平均を表示
select
bang,sum(uria) as 売上合計
from chap8
group by bang;

select
bang,avg(uria)
from chap8
group by bang;

・条件付きグループ表示(having)
・having:グループ化した値の抽出条件を設定する。
 ※抽出してからのグループ化ではない。
 [構文]
 select 集計したカラム from テーブル名 group by グループ化するカラム having 条件;

select bang,sum(uria) as '売上合計 200万以上' from chap8 group by bang
having sum(uria)>200;


・練習
select bang,avg(uria)
from chap8
where uria>50
group by bang
order by avg(uria) desc;

1.
select concat('合計は',sum(uria),'万円です') as '売上' from chap8;

2.
select bang,avg(uria),tuki
from chap8
group by bang
having avg(uria)>=120
order by avg(uria) desc;


■参考
本:基礎からのMySQL
http://dev.classmethod.jp/server-side/db/difference-where-and-having/