LoginSignup
64
61

More than 5 years have passed since last update.

SQLで同一グループの中で最大/最小のレコードを取得する

Last updated at Posted at 2017-05-24

やりたいこと

同じカテゴリの中での最高値の商品を、1件ずつ取得したいみたいなやつ。

下の例でいうと ★ のレコードを抽出したい。

sql_1.png

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;

結果

sql_2.png

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
;

結果

sql_3.png

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
    )
;

結果

sql_4.png

おしまい。

もっと簡単にやる方法ないだろか。

64
61
6

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
64
61