2011-12-01 121 views
0

根據當前記錄與先前記錄之間的比較,需要幫助更新字段/列「IsLatest」。我使用的是CTE的語法,我可以獲取當前和前一個記錄,但是我無法根據當前和前一個記錄的字段/列「值」更新我所需要的字段/列「IsLatest」。根據當前記錄值和先前記錄值更新字段/列

電流輸出

Dates     Customer Value IsLatest 
2010-01-01 00:00:00.000 1   12 1 

Dates     Customer Value IsLatest 
2010-01-01 00:00:00.000 1   12 0 
2010-01-02 00:00:00.000 1   30 1 

Dates     Customer Value IsLatest 
2010-01-01 00:00:00.000 1   12 0 
2010-01-02 00:00:00.000 1   30 0 
2010-01-03 00:00:00.000 1   13 1 

預期的最終輸出

Dates     Customer Value ValueSetId IsLatest 
2010-01-01 00:00:00.000 1   12  12   0 
2010-01-01 00:00:00.000 1   12  13   0 
2010-01-01 00:00:00.000 1   12  14   0 

2010-01-02 00:00:00.000 1   30  12   0 
2010-01-02 00:00:00.000 1   30  13   0 
2010-01-02 00:00:00.000 1   30  14   0 

2010-01-03 00:00:00.000 1   13  12   0 
2010-01-03 00:00:00.000 1   13  13   0 
2010-01-03 00:00:00.000 1   13  14   0 

2010-01-04 00:00:00.000 1   14  12   0 
2010-01-04 00:00:00.000 1   14  13   0 
2010-01-04 00:00:00.000 1   14  14   1 
+0

請問你的CTE樣子? –

+0

;具有CustCTE AS(SELECT客戶, 價值, 日期, ROW_NUMBER()OVER(PARTITION BY客戶ORDER BY日期)ROWNUM FROM @Customers), –

回答

0
;WITH a AS 
(
SELECT 
    Dates Customer Value, 
    row_number() over (partition by customer order by Dates desc, ValueSetId desc) rn 
FROM @Customers) 
SELECT Dates, Customer, Value, case when RN = 1 then 1 else 0 end IsLatest 
FROM a 
+0

喜t-clausen.dk,感謝這一點。我有類似於上面的代碼,但是,我沒有使用DESC,因爲我的想法是使用當前和以前的記錄,這讓我陷入了一種轉折。 –

+0

嗨t-clausen.dk,只是另一個問題,如果上表中有另一個字段唯一標識一行,但上面的輸出仍需要相同,我將如何更改代碼。示例每個日期,每個客戶你有3個不同的值。附加字段「PeriodSetId」以小時E.g 12,15 14等爲單位標識記錄。 –

+0

@LindsayFisher不確定你在問什麼,你能否用預期的結果和testdata來改變你的問題來說明? –

相關問題