使用步骤1

时间:2017-01-15 00:44:08

标签: 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,它将使用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。

非常感谢

1 个答案:

答案 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

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

  • 第n行将具有avg_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