SQL Server:删除重复项并添加列

问题描述 投票:0回答:2

我有一个表有重复记录,这是表的样子。

ID Date             Status      ModifiedBy
------------------------------------------
1  1/2/2019 10:29   Assigned(0) xyz
1  1/2/2019 12:21   Pending(1)  abc
1  1/4/2019 11:42   Completed(5)abc
1  1/20/2019 2:45   Closed(8)   pqr
2  9/18/2018 10:05  Assigned(0) xyz
2  9/18/2018 11:15  Pending(1)  abc
2  9/21/2018 11:15  Completed(5)abc
2  10/7/2018 2:46   Closed(8)   pqr

我想要做的是采取最小日期值,但我想添加额外的列PendingStartDatePendingEndDate

  • PendingStartDate:ID进入待处理状态的日期
  • PendingEndDate:ID从待处理状态变为任何其他状态的日期

所以我的最终输出应该是这样的

ID AuditDate        Status      ModifiedBy PendingStartDate PendingEndDate
---------------------------------------------------------------------------
1  1/2/2019 10:29   Assigned(0) xyz        1/2/2019 12:21   1/4/2019 11:42
2  9/18/2018 10:05  Assigned(0) abc        9/18/2018 11:15  9/21/2018 11:15

任何有关如何做到这一点的帮助表示赞赏。

谢谢

sql sql-server
2个回答
0
投票

我想你想要条件聚合:

select id, min(date) as auditdate,
       max(case when seqnum = 1 then status end) as status,
       max(case when seqnum = 1 then modifiedBy end) as modifiedBy,
       min(case when status like 'Pending%' then date end) as pendingStartDate,
       max(case when status like 'Pending%' then next_date end) as pendingEndDate
from (select t.*,
             row_number() over (partition by id order by date) as seqnum,
             lead(date) over (partition by id order by date) as next_date
      from t
     ) t
group by id;

0
投票

请试试这个:

    Declare @Tab Table(Id int, [Date] DATETIME,[Status] Varchar(25),ModifiedBy varchar(10))

    Insert into @Tab
    SELECT 1,'1/2/2019 10:29','Assigned(0)','xyz' Union All
    SELECT 1,'1/2/2019 11:29','Started(0)','xyz' Union All
    SELECT 1,'1/2/2019 12:21','Pending(1)','abc'  Union All
    SELECT 1,'1/2/2019 12:21','In-Progress(1)','abc'  Union All
    SELECT 1,'1/4/2019 11:42','Completed(5)','abc'Union All
    SELECT 1,'1/20/2019 2:45','Closed(8)','pqr'   Union All
    SELECT 2,'9/18/2018 10:05','Assigned(0)','xyz'Union All
    SELECT 2,'9/18/2018 11:15','Pending(1)','abc' Union All
    SELECT 2,'9/21/2018 11:15','Completed(5)','abc' Union All
    SELECT 2,'10/7/2018 2:46','Closed(8)','pqr'


    ;with cte As
    (
     Select * ,lead(date) over (partition by id order by date) as pendingStartDate
     from @Tab
     Where Status in ('Assigned(0)','Pending(1)','Completed(5)')
    )

    ,cte2 As
    (
        Select * , lead(pendingStartDate) over (partition by id order by date) As pendingEndDate
        from cte
    )

    Select * from cte2 where Status ='Assigned(0)'

正如您在评论中提到的,我在Assigned,pending和completed之间包含了一些状态。

© www.soinside.com 2019 - 2024. All rights reserved.