Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

sql server - How to retrieve only the records where stat changes?

I want to get same output:

I want to get the same output

using the following sample data

create table x
(
     id int, 
     date datetime, 
     stat int
)

insert into x 
values (1, '2017-01-01', 100), (1, '2017-01-03', 100), (1, '2017-01-05', 100),
       (1, '2017-01-07', 150), (1, '2017-01-09', 150), (1, '2017-02-01', 150),
       (1, '2017-02-02', 100), (1, '2017-02-12', 100), (1, '2017-02-15', 100),
       (1, '2017-02-17', 150), (1, '2017-03-09', 150), (1, '2017-03-11', 150),
       (2, '2017-01-01', 100), (2, '2017-01-03', 100), (2, '2017-01-05', 100),
       (2, '2017-01-07', 150), (2, '2017-01-09', 150), (2, '2017-02-01', 150),
       (2, '2017-02-02', 100), (2, '2017-02-12', 100), (2, '2017-02-15', 100),
       (2, '2017-02-17', 150), (2, '2017-03-09', 150), (2, '2017-03-11', 150)

I tried to use something like this

with a as
(
    select 
        id, date,
        ROW_NUMBER() over (partition by date order by id) as rowNum  
    from 
        x
), b as 
(
     select 
         id, date,
         ROW_NUMBER() over (partition by id, stat order by date) as rowNum   
     from 
         x
)
select min(b.date)  
from a
join b on b.id = a.id
having max(a.date) > max(b.date)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What you are looking for is a scenario, where you only have islands. In this scenario what defines the start of an island is a change in the stat value within a id, while evaluating the dataset in date order.

The lag window function is used below to compare values across rows, and see if you need to include it in the output.

select b.id
, b.stat
, b.date
from (
    select a.id
    , a.date
    , a.stat
    , case lag(a.stat,1,NULL) over (partition by a.id order by a.date asc) when a.stat then 0 else 1 end as include_flag
    from x as a
    ) as b
where b.include_flag = 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...