How to retrieve data from SQL Server based on below example?

后端 未结 1 1201
时光取名叫无心
时光取名叫无心 2021-01-16 06:38

Actually I posted a similar question related to this in here How to retrieve data from SQL Server as required below? and now I needed some changes in that so please see this

相关标签:
1条回答
  • 2021-01-16 07:35

    Maybe you can use a solution like below See working demo

    declare @d date='2018-Jun-03'
    
    ; with Indexer as 
    (
        select 
            *, 
            rn= row_number() over(partition by CustName order by RecordedTime),
            rn2=row_number() over(partition by CustName order by RecordedTime desc)
        from records
    )
    ,GetValidCustomerRecords as
    (
        select 
            CustName,
            Country,
            RecordedTime,
            Audit   = case when cast(RecordedTime as date)=@d and rn=1 then 'add' else 'change' end,
            History = case 
                        when cast(RecordedTime as date)=@d and rn=1 
                        then 'new' 
                        when cast(RecordedTime as date)<@d and rn=1 
                        then 'before'
                        else 'current' end
        from Indexer i 
        where CustName in
        (
        select 
            distinct CustName 
        from records
        where cast(RecordedTime as date)=@d
        ) 
        and (rn=1 or rn2=1) and cast(RecordedTime as date)<=@d
    )
    
    select * from GetValidCustomerRecords
    order by CustName, RecordedTime
    
    0 讨论(0)
提交回复
热议问题