即使用我的英语也难以解释,所以我将通过以下示例展示我想要的内容:
例如,我有一个像:
这样的表日期 ID Val
SomeDate.... 1 0
SomeDate.... 2 0
SomeDate.... 2 0
SomeDate.... 1 0
SomeDate.... 1 0
SomeDate.... 1 1
SomeDate.... 1 1
SomeDate.... 2 1
SomeDate.... 1 0
SomeDate.... 2 0
SomeDate.... 1 0
SomeDate.... 1 1
所以我想只注册更改值,如:
SomeDate.... 1 1 //registered 0 -> 1 for ID 1
SomeDate.... 2 1 //registered 0 -> 1 for ID 2
SomeDate.... 1 0 //registered 1 -> 0 for ID 1
SomeDate.... 2 0 //registered 1 -> 0 for ID 2
SomeDate.... 1 1 //registered 0 -> 1 for ID 1
MS SQL SERVER 2008
也许某人有一个例子或任何关于如何实现这些变化的想法,谢谢。
答案 0 :(得分:2)
以下内容可能会起到作用。
;With RankedDates As
(
Select T1.[Date], T1.ID, T1.Val
, Row_Number() Over( Partition By T1.ID Order By T1.[Date] ) As Num
From SourceTable As T1
)
Select T1.[Date], T1.ID
, T1.Val As InitialValue
, T2.Val As ChangedToValue
, T2.[Date] As ChangedDate
From RankedDates As T1
Join RankedDates As T2
On T2.ID = T1.ID
And T2.Num = T1.Num + 1
And T2.Val <> T1.Val
Order By T1.ID