重複データの抽出と件数取得
2016/04/12
どう説明すればいいかが分からない。
具体例
言葉でアレコレ説明するのが面倒なので、具体的にメモっていく。
使うテーブル
name | taste |
---|---|
鳥精 | タレ |
鳥精 | 塩 |
鳥精 | 味噌 |
豚精 | タレ |
豚精 | 塩 |
豚精 | 味噌 |
ひな皮 | タレ |
ひな皮 | 塩 |
丸ごとシマウマ | タレ |
丸ごとシマウマ | 塩 |
欲しい結果
「taste」で「タレ」と「味噌」を持つ「name」の件数が欲しい。
要は「2」が返ってきてくれたらOK。
重複データの抽出
いきなり件数を出したいんだけど・・・わからないのでひとまず「taste」で「タレ」と「味噌」を持つデータの抽出。
▼クエリ
select name
from xxx
where taste in (‘タレ’,’味噌’)
group by name having count(name)>=2;
from xxx
where taste in (‘タレ’,’味噌’)
group by name having count(name)>=2;
※「タレと味噌」の2つだから「count(name)>=2」にしている。
▼結果
name |
---|
鳥精 |
豚精 |
間違った例と結果
▼クエリ
select name
from xxx
where taste in (‘タレ’,’味噌’)
group by name;
from xxx
where taste in (‘タレ’,’味噌’)
group by name;
▼結果
name |
---|
鳥精 |
豚精 |
ひな皮 |
丸ごとシマウマ |
※「タレ」か「味噌」を含むデータが返ってきた。
重複データの抽出
やりかたがわからないので・・・サブクエリにしてみた。
▼クエリ
select count(*) from (
select name
from xxx
where taste in (‘タレ’,’味噌’)
group by name having count(name)>=2
) as hoge;
select name
from xxx
where taste in (‘タレ’,’味噌’)
group by name having count(name)>=2
) as hoge;
▼結果
count(*) |
---|
2 |