根据结束日期和记录数的条件计算 SQL 中的平均值

Calculate average in SQL based on condition for end date and number of records

我想计算类似于下面 table 中的记录的平均值(这只是一个示例,值无关紧要):

我有这样的查询:

SELECT Id,
AVG(Value) OVER(partition by ID Order by [date] rows between 2 preceding and current row) as avg_value,
FROM [table]
WHERE Code = 'SLS' --- there are more codes usually

我想添加但无法决定如何正确添加的条件是:

  1. 仅当每个 Id 的最大值 Date 为当年 >= 减去 1
  2. 时才计算平均值
  3. 仅当我有我指定的年数值时才计算平均值,在本例中为 3。

两个条件都必须满足。在这种情况下,Id = 2 甚至不满足其中一个条件。

您可以使用条件聚合处理第一个条件:

SELECT Id,
       AVG(CASE WHEN date > dateadd(year, -1, date) THEN Value END)
           OVER (partition by ID
                 order by [date] rows
                 between 2 preceding and current row
                ) as avg_value
FROM [table]
WHERE Code = 'SLS' --- there are more codes usually

我找到了一个似乎有效的解决方案:

SELECT Id,
AVG(Value) OVER(partition by ID Order by [date] rows between 2 preceding and current row) as avg_value,
FROM (
      SELECT *, 
             Max([Date]) OVER(partition by Id, Code) as MaxDate, 
             COUNT(*) OVER(partition by Id, Code) as RecordsPerCode
      FROM [table]
      WHERE Code = 'SLS'
  ) a
  WHERE 1=1 
  AND YEAR(MaxDate) = YEAR(DATEADD(year, -1, GETDATE()))
  AND RecordsPerCode >= 3 
  

如有任何建议或建议,我们将不胜感激。