【问题标题】:How to calcutale the average of a value for last three rows for every distinct id using sql?如何使用sql计算每个不同ID的最后三行的平均值?
【发布时间】:2022-01-18 17:42:39
【问题描述】:

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

{
"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"
},

【问题讨论】:

  • 希望您的 DBMS 具有窗口聚合 avg(..) over(..)
  • 您使用的是哪个 dbms?
  • @jarlh MySQL...
  • @Serg 我正在使用 MySQL
  • MySql 从 8.0 开始支持窗口函数

标签: mysql sql select group-by average


【解决方案1】:

MySql 从 8.0 开始支持窗口函数。获取 location_idapplicable_datetry 的最后 3 个项目

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

根据需要应用聚合。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-09
    • 2019-04-03
    • 1970-01-01
    • 2017-02-16
    • 2014-01-24
    • 1970-01-01
    • 2021-04-26
    • 1970-01-01
    相关资源
    最近更新 更多