在SQL中获取上次更改日期

时间:2015-03-02 20:25:01

标签: sql sql-server

StockCode   TimeStamp          UnitPrice    TrnDate
---------------------------------------------------------------
360120      0x000000000DBE9EED  16.8000 2015-02-13 0:00:00.000
360120      0x000000000DBEE175  16.8000 2015-02-17 00:00:00.000
360120      0x000000000DC177AC  16.8000 2015-02-24 00:00:00.000
360120      0x000000000DC1EEFB  16.0000 2015-02-25 00:00:00.000
360120      0x000000000DC1E9BE  16.8000 2015-02-25 00:00:00.000
360120      0x000000000DC261CE  16.0000 2015-02-27 00:00:00.000
360120      0x000000000DC2628D  16.8000 2015-02-27 00:00:00.000 **
360120      0x000000000DFC46EA  16.8000 2015-03-02 00:00:00.000

查询需要返回2015-02-27,其中价格从16.000到16.8000, 这是价格历史记录表中此料品的最后一次价格变动日期。 我编写它的方式,只有当价格没有变回该股票代码表中存在的价格时,它才有效。

SELECT 
    MAX(MinTrnDate) as LastTrnDate
FROM 
    (SELECT 
         a.UnitPrice, MIN(TrnDate) as MinTrnDate 
     FROM 
         (SELECT   
             ph.StockCode,
             CONVERT(DECIMAL(18,4), (ph.InvoiceValue/ ph.InvoiceQty)) as  UnitPrice,
             ph.TrnDate
          FROM 
             ArSalesMove ph 
          JOIN 
             ArCustomer c WITH(NOLOCK) on ph.Customer = c.Customer  
          WHERE   
             LTRIM(RTRIM(ph.StockCode)) = '360120'
             AND (ph.InvoiceValue/ ph.InvoiceQty) > 0
             AND c.PriceCode = 'A') AS a
     WHERE 
         a.UnitPrice > 0
     GROUP BY a.UnitPrice) AS b
HAVING 
     MIN(CONVERT(DECIMAL(18, 2), UnitPrice)) <> MAX(CONVERT(DECIMAL(18, 2), UnitPrice)) --Used to exclude stockcodes with no change...

1 个答案:

答案 0 :(得分:0)

对于SQL Server 2012或更高版本:

;WITH
    cte AS
    (
        SELECT  *,
                LAG(UnitPrice, 1) OVER (PARTITION BY StockCode ORDER BY TrnDate) AS LastPrice
        FROM    PriceHistory
    )

SELECT      StockCode, MAX(TrnDate)
FROM        cte
WHERE       UnitPrice != LastPrice
GROUP BY    StockCode

对于SQL Server 2005及更高版本:

;WITH
    cte AS
    (
        SELECT  *,
                ROW_NUMBER() OVER (PARTITION BY StockCode ORDER BY TrnDate) AS RowNumber
        FROM    PriceHistory
    )

SELECT      c2.StockCode, MAX(c2.TrnDate)
FROM        cte c1
INNER JOIN  cte c2 ON c1.StockCode = c2.StockCode AND c1.RowNumber + 1 = c2.RowNumber
WHERE       c1.UnitPrice != c2.UnitPrice
GROUP BY    c2.StockCode