我想知道是否有可能内在加入最大的值(value)。
举个例子
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
最佳答案
您的要求可以更简单地表达为:
use the greater of
VehicleWeight
andVehicleWeightTotal
when joining
这是在 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
范围每一边的声明。
关于sql - INNER JOIN 实现最大值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7394095/