2015-03-02 123 views
-1
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年2月27日,其中的價格去的形式向16.000 16.8000, 這是在價格歷史表這個項目的最後價格的更改日期。 我寫它的方式是,查詢只在價格沒有變回表格中存在的股票代碼價格時才起作用。獲取最後更改日期在SQL

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... 
+0

我懷疑這是有可能使用窗口功能可以輕鬆解決,但他們在所有RDBMS上不受支持。你使用的是什麼RDBMS? – JNevill 2015-03-02 20:26:28

+0

這是SQL Server中的存儲過程。 – Arraylist 2015-03-02 20:30:49

+3

SQL Server _ _ _ _? – 2015-03-02 20:42:49

回答

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 
+0

工作就像一個魅力。 – Arraylist 2015-03-05 18:14:16