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