2016-11-10 71 views
-1

我想爲每個城市選擇2輛最貴的汽車。爲每個城市選擇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); 

輸出應該是相同的目錄下面的所有列:

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; 

取決於:

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 

回答

相關問題