我有一个包含item id
,purchase date
和item unit cost
的购买明细表。
我想通过从每个商品ID中选择最新的前2条记录来获得平均商品购买成本。
Item id, purchase date, unitprice
1 3/1/2012 10
1 3/11/2012 8
2 3/1/2012 10
2 3/11/2012 10
1 2/1/2012 9
3 3/1/2012 10
3 3/11/2012 1
3 3/12/2012 13
我正在使用sql server 2008 r2
答案 0 :(得分:4)
试试这个:
;WITH CTE AS (
SELECT [Item id], [purchase date], unitprice,
ROW_NUMBER() OVER(PARTITION BY [Item id] ORDER BY [purchase date] DESC) rn
FROM your_table
)
SELECT [Item id], [purchase date], unitprice
FROM CTE
WHERE rn < 3
我不确定如何使用最新的两条记录来计算平均值,但如果需要,请确保可以在查询中添加GROUP BY
。
也许是这样的:
-- CTE here --
SELECT [Item id], AVG(unitprice)
FROM CTE
WHERE rn < 3
GROUP BY [Item id]
答案 1 :(得分:2)
;WITH CTE AS (
SELECT [Item id]
, [purchase date]
, [unitprice]
, [avg] = AVG([unitprice]) OVER(PARTITION BY [Item id])
, [rnum] = ROW_NUMBER() OVER(PARTITION BY [Item id] ORDER BY [purchase date] DESC)
FROM T
)
SELECT [Item id], [purchase date], [unitprice], [avg]
FROM CTE
WHERE rnum < 3
答案 2 :(得分:0)
SELECT AVG(unitprice) as price from yourtablename
where unitprice IN
(
SELECT TOP 3 (unitprice) from yourtablename
where itemid='1'
ORDER BY unitprice Desc
);
通过下拉列表或文本框获取itemid。 对你有用吗?