开发者

How to select only changing values

开发者 https://www.devze.com 2023-02-15 00:15 出处:网络
It\'s hard to explain even with my English so I\'m going to show what I want through the following example :

It's hard to explain even with my English so I'm going to show what I want through the following example :

For example I have a table like:

Date 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

So I want to register only changing values like :

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 ->开发者_Python百科 1 for ID 1

MS SQL SERVER 2008

maybe someone an example or any thoughts as to how can I realize these changes, thank you.


Something like the following might do the trick.

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

精彩评论

暂无评论...
验证码 换一张
取 消