如何使用 sql 计算每个不同 ID 的最后三行的平均值?

How to calcutale the average of a value for last three rows for every distinct id using sql?

我有一个数据库,其中包含 2 个不同位置三天的预报。对于每一天,每小时都有许多预报。 我想计算每天最后 3 次预报的每个位置的平均温度。位置保存为“location_id”,日期在名称为“applicable_date”的列中,“创建”包含小时数。
这里可以看到一个export

{
"location": "London",
"weather_state_name": "Heavy Rain",
"weather_state_abbr": "hr",
"wind_direction_compass": "WSW",
"created": "2021-09-27T00:59:15.571283Z",
"applicable_date": "2021-10-05",
"min_temp": "11.58",
"max_temp": "14.38",
"the_temp": "13.24",
"wind_speed": "5.312723693629206",
"wind_direction": "237.0",
"air_pressure": "996.0",
"humidity": "70",
"visibility": null,
"predictability": "77"
},
{
"location": "London",
"weather_state_name": "Light Cloud",
"weather_state_abbr": "lc",
"wind_direction_compass": "WNW",
"created": "2021-09-28T00:59:14.295872Z",
"applicable_date": "2021-10-06",
"min_temp": "7.83",
"max_temp": "13.27",
"the_temp": "12.48",
"wind_speed": "2.709178398154776",
"wind_direction": "298.0",
"air_pressure": "1022.0",
"humidity": "45",
"visibility": null,
"predictability": "70"
},
{
"location": "London",
"weather_state_name": "Heavy Rain",
"weather_state_abbr": "hr",
"wind_direction_compass": "S",
"created": "2021-09-29T00:59:13.083990Z",
"applicable_date": "2021-10-07",
"min_temp": "9.36",
"max_temp": "15.19",
"the_temp": "15.19",
"wind_speed": "2.5911178716296828",
"wind_direction": "183.99999999999997",
"air_pressure": "1021.0",
"humidity": "57",
"visibility": null,
"predictability": "77"
},

MySql 从 8.0 开始支持 window 函数。要获取 location_idapplicable_date 的最后 3 项,请尝试

select *
from (
   select *,
     row_number() over(partition by location_id, applicable_date order by created desc) rn
) t
where rn <= 3

根据需要应用聚合。