2016-08-24 23 views
2

我有一個有像下面的數據:如何更新基於此前的紀錄

CourseKey UserKey UsersPk1 MSGMAIN Date CummCount Recent Count 
32332  33  33  2016-08-22  2   0 
32332  33  33  2016-08-24  6   0 

我基本上是想說:

Update table 
set Recent Count = (CummCount for Latest date - Cummcount for previous date); 
在這種情況下,這將是4

我對如何使用日期在這種情況下

+0

而近期計數的更新應適用於記錄日期最新的唯一 –

+0

格式正確樣本數據.. –

+0

什麼數據庫您使用的? –

回答

0

使用拍攝前一行困惑:

WITH cte AS (
    SELECT [MSGMAIN Date], 
      CummCount - LAG(CummCount, 1, 0) OVER (ORDER BY [MSGMAIN DATE]) AS newCount 
    FROM ff 
) 

UPDATE ff 
SET [Recent Count] = cte.newCount 
FROM ff 
INNER JOIN cte 
    ON ff.[MSGMAIN Date] = cte.[MSGMAIN Date] 
+1

'LAG'不適用於SQL 2008 – ZLK

+1

現在可以使用SQL 2012。 –

+0

答覆復活! –