最近3次购买的平均值

时间:2015-10-28 11:18:14

标签: sql sql-server sql-server-2008

我需要帮助来创建查询来计算每种产品的最近3次购买的平均价格... 如图所示:

enter image description here

我该怎么做?

2 个答案:

答案 0 :(得分:1)

您可以使用窗口函数和avg()执行此操作。我们的想法是按购买日期列举购买,并选择最近的三个进行汇总:

select product, avg(buyprice)
from (select t1.*,
             row_number() over (partition by product order by purchase desc) as seqnum
      from table1
     ) t1
where seqnum <= 3
group by product;

答案 1 :(得分:1)

可能会有效

;WITH CTE AS (
                  SELECT ROW_NUMBER() OVER(PARTITION BY Product ORDER BY Purchase DESC) AS RN
,Purchase,
,cost
   FROM   Table1
              )
SELECT *
      ,AVG(cost) OVER(PARTITION BY Product) AS Average
FROM   CTE
WHERE  RN BETWEEN 1 AND 3