为每个城市选择2辆最贵的汽车

时间:2016-11-10 07:19:49

标签: sql postgresql greatest-n-per-group

我想为每个城市选择2辆最贵的汽车。

下面的DDL:

create table city_car 
(
    id bigserial,
    city varchar(255),
    car varchar(255),
    price int,
    primary key (id)
);

insert into city_car(city, car, price) 
values
    ('los angeles', 'kia rio', 550),
    ('los angeles', 'audi a4', 1800),
    ('los angeles', 'lexus nx', 2000),
    ('los angeles', 'chevrolet camaro', 2800),
    ('los angeles', 'mazda 6', 1300),
    ('moscow', 'mazda 3', 1000),
    ('moscow', 'kia cerato', 1000),
    ('moscow', 'lexus nx', 2100),
    ('moscow', 'lexus lx', 5000),
    ('moscow', 'bmw x6', 5000),
    ('prague', 'skoda octavia', 1000);

输出应与下面列表中的所有列相同:

city          name              price
-----------------------------------------
'los angeles' 'lexus nx'         2000 
'los angeles' 'chevrolet camaro' 2800 
'moscow'      'lexus lx'         5000 
'moscow'      'bmw x6'           5000 
'prague'      'skoda octavia'    1000

1 个答案:

答案 0 :(得分:2)

问题通常使用window functions解决:

select city,car,price
from (
  select *, 
         dense_rank() over (partition by city order by price desc) as rnk
  from city_car
) t
where rnk <= 2
order by city, price desc;

根据您希望如何处理出现两次的最高值,您可以将dense_rank()更改为row_number()

在线示例:http://rextester.com/ALKZ85776