gpt4 book ai didi

用于计算每 n 行的平均值的 SQL 查询,步骤 1

转载 作者:行者123 更新时间:2023-11-29 13:21:07 25 4
gpt4 key购买 nike

我有这样的数据

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,它将通过步骤 1 返回每 3 行的平均分数的最大值

例如。

1st AVG = AVG(score) WHERE id IN 1,2,3

2st AVG = AVG(score) WHERE id IN 2,3,4

还有其他人...

最后,我需要平均值的最大值。

非常感谢

最佳答案

使用带有窗口框架规范的 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

您应该从该结果中排除最后 2 行。因为

  • 第 n 行将有 avg_score=score 因为窗口中只有一行
  • 第 (n-1) 行的 avg_score 将为(第 n 行的值 + 第 n-1 行的值)/2,因为窗口中只有 2 行

要排除它们,请使用

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

关于用于计算每 n 行的平均值的 SQL 查询,步骤 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41656620/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com