我有一些像这样的数据
KEYS: {id, score, user_id}
VALUES:
{1, 23, 2},
{1, 23, 2},
{2, 27, 2},
{3, 42, 2},
{4, 71, 2},
{5, 11, 2}
我需要SQL,它将使用STEP 1返回每3行AVERAGE得分的MAX值
例如。
1st AVG = AVG(得分)WHERE id IN 1,2,3
第2个AVG = AVG(得分)WHERE id IN 2,3,4
还有其他人......
最后,我需要MAX VALUE OF AVERAGES。
非常感谢
答案 0 :(得分:0)
使用带有窗口框架规范的avg
窗口函数来考虑当前行和接下来的2行。我假设id
列是表中的主键。
select max(avg_score)
from (select avg(score) over(order by id rows between current row and 2 following) as avg_score
from t
) x
您应该从此结果中排除最后两行。因为
要排除他们使用,
select max(avg_score)
from (select row_number() over(order by id desc) as rn
,avg(score) over(order by id rows between current row and 2 following) as avg_score
from t
) x
where rn > 2 --excluding the last 2 rows
如果需要为每个user_id完成上述操作,请添加partition by
规范,如图所示。
select distinct user_id,max(avg_score) over(partition by user_id) as max_avg
from (select row_number() over(partition by user_id order by id desc) as rn
,avg(score) over(partition by user_id order by id rows between current row and 2 following) as avg_score
from t
) x
where rn > 2 --excluding the last 2 rows