我在SQL Server表中有销售交易,如下所示:
ItemNumber, TrxDate, UnitPrice
ABC, 1/1/2013, 10.00
ABC, 2/1/2013, 10.00
ABC, 3/1/2013, 13.00
ABC, 4/1/2013, 14.00
ABC, 5/1/2013, 14.00
XYZ, 1/1/2013, 18.00
XYZ, 2/1/2013, 18.00
XYZ, 3/1/2013, 20.00
XYZ, 4/1/2013, 20.00
XYZ, 5/1/2013, 20.00
我需要一个存储过程来生成看起来像这样的输出
ItemNumber, LastPrice, PriorPrice
ABC, 14.00, 13.00
XYZ, 20.00, 18.00
答案 0 :(得分:0)
您可以先使用lag()
功能查找价格变化时间:
select ItemNumber,
max(case when seqnum = 1 then Price end) as LastPrice,
max(case when seqnum = 2 then Price end) as PriorPrice
from (select t.*, row_number() over (partition by ItemNumber order by TrxDate desc) as seqnum
from (select t.*,
lag(Price) over (partition by ItemNumber order by TrxDate) as PrevPrice
from t
) t
where Price <> PrevPrice or PrevPrice is NULL
) t
group by ItemNumber;
只能从SQL Server 2012开始提供延迟。
如果你没有lag()
,你可以用相关的子查询做同样的事情:
select ItemNumber,
max(case when seqnum = 1 then Price end) as LastPrice,
max(case when seqnum = 2 then Price end) as PriorPrice
from (select t.*, row_number() over (partition by ItemNumber order by TrxDate) as seqnum
from (select t.*,
(select top 1 t2.Price
from t t2
where t.ItemNumber = t2.ItemNumber and
t.TrxDate > t2.TrxDate
order by t2.TrxDate desc
) as PrevPrice
from t
) t
where Price <> PrevPrice or PrevPrice is NULL
) t
group by ItemNumber;
答案 1 :(得分:0)
Assmunig SQL Server 2005 +:
;WITH CTE AS
(
SELECT *,
RN=ROW_NUMBER() OVER(PARTITION BY ItemNumber ORDER BY TrxDate DESC)
FROM ( SELECT ItemNumber,
MAX(TrxDate) TrxDate,
UnitPrice
FROM YourTable
GROUP BY ItemNumber,
UnitPrice) A
)
SELECT ItemNumber,
MIN(CASE WHEN RN = 1 THEN UnitPrice END) LastPrice,
MIN(CASE WHEN RN = 2 THEN UnitPrice END) PriorPrice
FROM CTE
GROUP BY ItemNumber