要获得最低2个值的滚动平均值的功能?

问题描述

这是我的示例数据,其中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列中的值。current_Rating从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

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...