简体   繁体   中英

How to update columns data based on previous rows of a result set

I am new to MS SQL server and I want to write a query to transform data from LHS to RHS. ( as shown in image below )

在此处输入图片说明

I have referred to answers given here and here but couldn't figure out the query completely because of grouping of result set on same id.

Any help is very much appreciated.
Thanks.

You don't need group by clause

On from clause , you can use 2 auto join to find next and previous rows using index.

On the select clause you need just adapt case when statement to implement your specific rules like this (not tested, but the idea is here) :

create table RHS as
select
    Curr.policy,
    case
    when prev.EventDate is null then Curr.policyIssueDate
    else EventDate 
    end as StartDate,
    case
    when next.EventDate is null then CURDATE()
    else EventDate 
    end as EndDate
from
    LHS Curr
    left join LHS next on
        Curr.INDEX+1= next.INDEX and
        Curr.policy = next.policy 
    left join LHS prev on
        Curr.INDEX-1= prev.INDEX and
        Curr.policy = prev.policy

For today date :

  • Mysql : CURDATE()
  • SQLServer : getdate()

Note : you can also use lead and lag window function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM