消除最低 2 个值的滚动平均值的功能?

Function to get rolling average with lowest 2 values eliminated?

这是我的示例数据,其中 current_Rating 列是我想要的输出。


Date         Name    Subject         Importance    Location     Time      Rating  Current_rating
12/08/2020   David   Work            1             London       -         -       4
1/08/2020    David   Work            3             London       23.50     4       3.66
2/10/2019    David   Emails          3             New York     18.20     3       4.33
2/08/2019    David   Emails          3             Paris        18.58     4       4
11/07/2019   David   Work            1             London       -         3       4
1/06/2019    David   Work            3             London       23.50     4       4
2/04/2019    David   Emails          3             New York     18.20     3       5
2/03/2019    David   Emails          3             Paris        18.58     5       -
12/08/2020   George  Updates         2             New York     -         -       2
1/08/2019    George  New Appointments5             London       55.10     2       -

我需要使用一个函数来获取 current_Rating column.The current_Rating 中的值 从每个名称的评级列中获取前 5 个结果,然后消除最低的 2 个结果,然后获取剩余 3 个的平均值。另外一些名称可能没有 5 个结果,所以如果 3 个或以下,我只需要获取结果的平均值,如果 4 个结果,我需要消除最低值并平均剩余 3。另外,为了获得正确的 5 个先前结果,需要按日期排序。这可能吗?感谢您提前抽出时间。

好痛!我认为最简单的方法可能是使用数组然后 unnest() 和聚合:

select t.*, r.current_rating
from (select t.*,
             array_agg(rating) over (partition by name order by date rows between 4 preceding and current row) as rating_5
      from t
     ) t cross join lateral
     (select avg(r) as current_rating
      from (select u.*
            from unnest(t.rating_5) with ordinality u(r, n)
            where r is not null
            order by r desc desc
            limit 3
           ) r
     ) r