2013-07-04 90 views
0

帶回只有最低的價格,我有兩個MSSQL表如下:SQL查詢 - 加入兩個表從表2

boat_data 

boat_prices 

船約船隻數據的數據房子行。每艘船都有一個獨特的編號(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

是這樣的:

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

哦,你的速度快,+++:在這種情況下d – mirkobrankovic

+0

他將只得到價格在 「早晨」 事業他們是最低的,他說最低的 – mirkobrankovic

+0

@mirkobrankovic:這就是傑森要求的:「*只帶回每艘船的最低價格*」。 –

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