2011-09-12 42 views
3

我想知道是否有可能加入腸子上的greates值。INNER JOIN上最大的價值

因此,例如

SELECT * 
FROM Vehicle v 
INNER JOIN VehicleCost vc ON v.VehicleWeight > vc.WeightFrom AND c.VehicleWeight < vc.WeightTo 

但如果v.VehicleWeightTotal> v.VehicleWeight我想,要更換v.VehicleWeight的內連接。所以這可能對每輛車都是不同的加入。

我怎麼會去這樣做內加入該檢查?

樣品:

tblVehicle 
VehicleId VehicleWeight VehicleWeightTotal 
1    12    15 
2    1    8 
3    16    20 

tblVehicleCost 
WeightFrom WeightTo Dollars 
0    5   1 
6    11  8 
12    16  9 
17    20  15 

所以:

Vehicle 1 = 9 
Vehicle 2 = 8 
Vehicle 3 = 15 
+0

請顯示一些示例數據和預期結果。一般來說,將邏輯放入連接並不是一個好主意。 – HLGEM

+0

已添加詳細信息 – mameesh

回答

5

你的要求可以更簡單地表述爲:

在加入時所使用的VehicleWeightVehicleWeightTotal更大

這是你如何表達,在SQL:

SELECT * 
FROM Vehicle v 
INNER JOIN VehicleCost vc 
    ON (case 
     when VehicleWeightTotal > VehicleWeight then VehicleWeightTotal 
     else VehicleWeight 
     end) between vc.WeightFrom AND vc.WeightTo; 

我把改變你的範圍檢查使用between的自由,但如果它不是確定以匹配值等於範圍限制 - 即在您的查詢中使用>=<= - 然後僅對範圍的每一側重複case聲明。

4
SELECT * 
FROM Vehicle v 
INNER JOIN VehicleCost vc ON 
    case when v.VehicleWeight > v.VehicleWeightTotal then v.VehicleWeight 
     else v.VehicleWeightTotal end > vc.WeightFrom 
    AND case when v.VehicleWeight > v.VehicleWeightTotal then v.VehicleWeight 
     else v.VehicleWeightTotal end < vc.WeightTo 
+0

+1您比我稍微快點發帖:) – Bohemian

0

您可以使用派生表來定義VehicleWeightVehicleWeightTotal之間的較大權重列作爲CASE表達式。這樣,您就不必在連接條件中重複長表達式:

WITH GreaterWeights AS (
    SELECT 
    *, 
    GreaterWeight = CASE 
     WHEN VehicleWeightTotal > VehicleWeight THEN VehicleWeightTotal 
     ELSE VehicleWeight 
    END 
    FROM Vehicle 
) 
SELECT * 
FROM GreaterWeights v 
    INNER JOIN VehicleCost vc ON v.GreaterWeight > vc.WeightFrom 
          AND v.GreaterWeight < vc.WeightTo