SQL查询 - 加入两个表,只返回表2中的最低价格

时间:2013-07-04 10:53:41

标签: sql sql-server

我有两个MSSQL表如下:

boat_data

boat_prices

船数据包含有关船只的大量数据。每艘船都有一个唯一的ID(pricingRef) 船价为每艘船提供大量租赁价格,每艘船可以有任意数量的行。每行还有一个pricingRef值。 boat_prices表中的示例数据可能是:

pricingRef > pricingDescription > price

ASD1 > fullDay > 1500

ASD1 > perWeek > 9000

ASD1 > morning > 800

ASD2 > fullDay > 2000

ASD2 > perWeek > 12000

ASD2 > morning > 1100

我需要做的是从boat_data表中取回所有行并将其加入到boat_prices表中,只返回每艘船的最低价格。我编写了下面的SQL语句。问题是它真的很笨重而且很乱。我使用min(price)从boat_prices表中返回价格值,然后从boat_data表中明确请求每个字段,然后按boat_data表中的每个字段进行分组。

必须有更好的方法来实现这一目标。道歉我是SQL新手。请帮忙!

select 
min(price) as price,
boat_data.ID,
boat_data.boatRef,
boat_data.capacity,
boat_data.sleeps,
boat_data.fuelConsumption,
boat_data.yearBuilt,
boat_data.length,
boat_data.beam,
boat_data.engines,
boat_data.tender,
boat_data.boatName,
boat_data.cabins,
boat_data.speed,
boat_data.location,
boat_data.onSale,
boat_data.supplierID,
boat_data.boatClassID,
boat_data.pricingRef,
boat_data.crew,
boat_data.sportsEquipment 
from boat_data 
join boat_prices 
     on boat_data.pricingRef = boat_prices.pricingRef 
group by 
boat_data.ID,
boat_data.boatRef,
boat_data.capacity,
boat_data.sleeps,
boat_data.fuelConsumption,
boat_data.yearBuilt,
boat_data.length,
boat_data.beam,
boat_data.engines,
boat_data.tender,
boat_data.boatName,
boat_data.cabins,
boat_data.speed,
boat_data.location,
boat_data.onSale,
boat_data.supplierID,
boat_data.boatClassID,
boat_data.pricingRef,
boat_data.crew,
boat_data.sportsEquipment 
order by price

2 个答案:

答案 0 :(得分:2)

类似的东西:

select boat_data.*,
       t.min_price
from boat_data
  join (
     select pricingref, min(price) as min_price
     from boat_prices
     group by pricingref
  ) t on t.pricingref = boat_data.pricingref;

答案 1 :(得分:0)

也许:

SELECT bp.price,
       bd.*
FROM boat_data bd
JOIN boat_prices bp ON bd.pricingRef = bp.pricingRef
WHERE bp.price = (SELECT MIN(bp2.price)
                  FROM boat_prices bp2
                  WHERE bp2.pricingRef = bd.pricingRef)
ORDER BY bp.price