Sql 每组最接近的匹配?
我有一张类似的桌子:Sql 每组最接近的匹配?,sql,sql-server,Sql,Sql Server,我有一张类似的桌子: Motor MotorType CalibrationValueX CalibrationValueY A Car 1.2343 2.33343 B Boat 1.2455 2.55434 B1 Boat 1.4554 2.11211 C Car 1.4323 4.56555 D Car 1.5
Motor MotorType CalibrationValueX CalibrationValueY
A Car 1.2343 2.33343
B Boat 1.2455 2.55434
B1 Boat 1.4554 2.11211
C Car 1.4323 4.56555
D Car 1.533 4.6666
..... 500 entries
在我的SQL查询中,我试图找到CalibrationValueY的平均值,其中CalibrationValueX是一个特定值:
SELECT avg(CalibrationValueY), MotorType, Motor FROM MotorTable
WHERE CalibrationValueX = 1.23333
GROUP BY MotorType
这不会返回任何内容,因为没有正好等于1.23333的CalibrationValueX值
我能够分别为每个机动驾驶台找到最接近的匹配项,包括:
SELECT TOP 1 CalibrationValueY, FileSize, MotorType, Motor FROM MotorTable
where FileType = 'text' order by abs(FileSize - 1.23333)
然而,我不能让它与一组语句一起工作。
如果我按电机类型分组并搜索CalibrationValueX=1.23333,我将得到以下结果:
A Car 1.2343 2.33343
B Boat 1.2455 2.55434
使用
ROW\u NUMBER
和partitionby
组合每组的TOP 1
with cte as (
SELECT MotorType, CalibrationValueX, CalibrationValueY,
ROW_NUMBER() over (partition by MotorType order by abs(CalibrationValueX - 1.23333)) rn
from historyCR
)
SELECT *
from cte
where rn = 1
输出
我基本上有完全相同的解决方案:)@mellamokb很容易,花了我更长的时间编写sqlfiddle
| MotorType | CalibrationValueX | CalibrationValueY | rn |
|-----------|-------------------|-------------------|----|
| Boat | 1.2455 | 2.55434 | 1 |
| Car | 1.2343 | 2.33343 | 1 |