1

我已经尝试解决这个问题一段时间了,任何帮助将不胜感激。

我有桌子:

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

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

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

4

1 回答 1

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

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

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;
于 2013-01-28T20:03:05.887 回答