INNER JOIN最大的价值

时间:2011-09-12 21:11:20

标签: sql sql-server sql-server-2005

我想知道是否有可能加入greates值。

所以例如

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

但如果v.VehicleWeightTotal&gt; 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

3 个答案:

答案 0 :(得分: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和{{1}}查询 - 然后只需为范围的每一侧重复{{1}}语句。

答案 1 :(得分: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

答案 2 :(得分: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