Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
SQL查询,用于计算步骤1中每n行的平均值_Sql_Postgresql - Fatal编程技术网

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

SQL查询,用于计算步骤1中每n行的平均值,sql,postgresql,Sql,Postgresql,我有一些这样的数据 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行平均得分的最大值 比如说 第一个平均值=平均值(分数),其中id在1,2,3中 2st AVG=平均值(分数),其中id在2,3,4中 和其他人 最后,我需要平均值的最大值 非常感谢使用“代码> avg < /COD

我有一些这样的数据

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行平均得分的最大值

比如说

第一个平均值=平均值(分数),其中id在1,2,3中

2st AVG=平均值(分数),其中id在2,3,4中

和其他人

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


非常感谢

使用“代码> avg < /COD>窗口函数,使用窗口框规范来考虑当前行和下一行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行将具有平均分数=分数,因为窗口中只有一行
  • 第(n-1)行的平均得分为(第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
如果需要为每个用户id执行上述操作,请按规范添加一个分区,如图所示

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

您能否标记正在使用的实际dbms并删除无关的dbms。@vkp postgresql