SQLite | データ検索 | GROUP BYとHAVING
GROUP BYは集計のために行をグループ化し、HAVINGは集計後のグループを絞り込む。
GROUP BY
SELECT columns FROM table_name GROUP BY column1, column2;
create table user (name text, gender text, address text);
insert into user values ('devkuma', 'man', 'Seoul');
insert into user values ('kimkc', 'man', 'Busan');
insert into user values ('arikuma', 'woman', 'Seoul');
insert into user values ('happykuma', 'woman', 'Suwan');
insert into user values ('raccoon', 'man', 'Busan');
insert into user values ('mykuma', 'woman', 'Daejeon');
insert into user values ('yourkuma', 'man', 'Seoul');
select gender, count(*) from user group by gender;
select address, count(*) from user group by address;
select gender, address, count(*) from user group by gender, address;
性別の集計はman|4とwoman|3、住所の集計はBusan 2、Daejeon 1、Seoul 3、Suwan 1となる。SUMやAVGなどもグループ単位で使用できる。
HAVING
WHEREはグループ化前の行、HAVINGはグループ化後の集計結果を絞り込む。
select address, count(*) from user
group by address having count(*) >= 2;
結果はBusan|2とSeoul|3である。