我有一个与此类似的表格:
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 值。
我可以通过以下方式为每个 MotorTable 单独找到最接近的匹配:
SELECT TOP 1 CalibrationValueY, FileSize, MotorType, Motor FROM MotorTable
where FileType = 'text' order by abs(FileSize - 1.23333)
但是,我无法让它与 group by 语句一起使用。 我该如何做到这一点,以便如果我按 MotorType 分组并且正在搜索 CalibrationValueX = 1.23333,我会得到以下结果:
A Car 1.2343 2.33343
B Boat 1.2455 2.55434
最佳答案
使用ROW_NUMBER
和PARTITION BY
您可以为每个组组合TOP 1
<强> SQL Fiddle Demo
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
输出
| MotorType | CalibrationValueX | CalibrationValueY | rn |
|-----------|-------------------|-------------------|----|
| Boat | 1.2455 | 2.55434 | 1 |
| Car | 1.2343 | 2.33343 | 1 |
关于sql - 每组最接近的比赛?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32727901/