やりたいこと
同じカテゴリの中での最高値の商品を、1件ずつ取得したいみたいなやつ。
下の例でいうと ★ のレコードを抽出したい。
1. テーブル作ってデータ入れる
create table items (
id int not null primary key,
name varchar(100),
price int,
category varchar(100)
);
insert into items values(1, 'りんご', 190, 'くだもの');
insert into items values(2, 'みかん', 100, 'くだもの');
insert into items values(3, 'きゅうり', 80, '野菜');
insert into items values(4, '人参', 110, '野菜');
insert into items values(5, 'キャベツ', 110, '野菜');
insert into items values(6, '豚肉', 300, '肉');
insert into items values(7, '牛肉', 400, '肉');
2. カテゴリ毎に一番高い価格を抽出する
select category, max(price) as price from items group by category;
結果
3. 次に、それらのカテゴリ、価格の中で、一番小さい id を取得する。
サブクエリ使う。
select
category, price, min(id) as id
from
items
where
(category, price)
in
(
select
category
,max(price) as price
from
items
group by
category
)
group by
category, price
;
結果
4. あとは、その id で items を抽出する。
さらにサブクエリ。重そう。
select
*
from
items
where
id in (
select
min(id) as id
from
items
where
(category, price)
in
(
select
category ,max(price) as price
from
items
group by category
)
group by category, price
)
;
結果
おしまい。
もっと簡単にやる方法ないだろか。