Oracle从多个结果中选择min行

时间:2013-01-28 19:59:01

标签: sql oracle

我一直在尝试解决这个问题,任何帮助都会非常感激。

我有桌子:

distributor(distributor_name, distributor_id)
distributed(price, movie_id, distributor_id)
movie(title, movie_id)

每个发行商都有多个不同价格的电影记录。

我正在尝试为特定电影和分销商

选择最低价格

到目前为止,我已尝试过:

select min(Price), Distributor from
(select m.distributor_name as Distributor, d.price from 
distributors m, distributed d, movies mo
where
mo.title = 'Movie Name' and mo.movie_id = d.movie_id and d.distributor_id = m.distributor_id)
group by Distributor;

返回每个经销商的最低价格。

如果我跑:

select min(Price)
(select m.distributor_name as Distributor, d.price from 
distributors m, distributed d, movies mo
where
mo.title = 'Movie Name' and mo.movie_id = d.movie_id and d.distributor_id = m.distributor_id);

它只提供该特定电影的最低价格。

如何以最低价格获得经销商的名称?

1 个答案:

答案 0 :(得分:1)

根据您的Oracle版本,您可以使用row_number()

select price, distributor
from
(
  select d.price, 
    m.distributor_name as Distributor,
    row_number() over(order by d.price) rn
  from distributors m
  inner join distributed d
    on d.distributor_id = m.distributor_id
  inner join movies mo 
    on mo.movie_id = d.movie_id 
  where mo.title = 'Movie Name' 
) src
where rn = 1;

请参阅SQL Fiddle with Demo

如果你想扩展它并获得任何电影的最低价格,那么你可以按电影标题对数据进行分区:

select price, distributor
from
(
  select d.price, 
    m.distributor_name as Distributor,
    row_number() over(partition by mo.title order by d.price) rn
  from distributors m
  inner join distributed d
    on d.distributor_id = m.distributor_id
  inner join movies mo 
    on mo.movie_id = d.movie_id 
) src
where rn = 1;