0

我在这样的 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
4

2 回答 2

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;
于 2013-08-19T20:44:58.887 回答
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
于 2013-08-19T20:51:55.963 回答