值之间的平均差异 SQL

Average difference between values SQL

我正在尝试使用 SQL 找出值之间的差异,其中第二个值始终大于前一个值。

示例数据:

Car_ID | Trip_ID | Mileage
1       1         10,000
1       2         11,000
1       3         11,500
2       1         5,000
2       2         7,000
2       3         8,000

预期计算:

Car_ID: 1
(Trip 2 - Trip 1) = 1,000 
(Trip 3 - Trip 2) = 500
Average Difference: 750

Car_ID: 2
(Trip 2 - Trip 1) = 2,000 
(Trip 3 - Trip 2) = 1,000
Average Difference: 1,500

预期输出:

Car_ID | Average_Difference
1        750 
2        1,500

您可以使用聚合:

select car_id,
       (max(mileage) - min(mileage)) / nullif(count(*) - 1, 0)
from t
group by car_id;

也就是说,您定义的平均值是最大值减去最小值除以旅行次数减一。