SQL 服务器查询-更新重复记录

SQL Server Query-Update Duplicate Records

能否请任何人帮我解决 SQL 服务器查询。我想根据业务规则将 Table 1 条记录插入到 Table 2。

业务规则1-如果Ref_No.MsgCreatedDt相同不同则插入这些记录并更新第一个记录(备注 列)为空白,其余为重复。

业务规则2-如果Ref_No。相同,MsgCreatedDt 也相同,则只插入一条记录。

下面是输入输出。

输入:Table1

ID  Ref_No  MsgCreatedDt    Remarks
1   Ref1    22-03-2020 17:39    
2   Ref1    22-03-2020 17:42    
3   Ref1    22-03-2020 18:10    
4   Ref2    22-03-2020 16:11    
5   Ref2    22-03-2020 16:11    

输出:Table2

ID  Ref_No  MsgCreatedDt        Remarks
1   Ref1    22-03-2020 17:39    
2   Ref1    22-03-2020 17:42    Duplicate
3   Ref1    22-03-2020 18:10    Duplicate
4   Ref2    22-03-2020 16:11

具有ROW_NUMBER()window功能:

insert into Table2 (ref_no, msgcreateddt, remarks)
select t.ref_no, t.msgcreateddt,
  case when t.rn1 > 1 then 'Duplicate' end
from (  
  select *,
    row_number() over (partition by ref_no order by msgcreateddt) rn1,
    row_number() over (partition by ref_no, msgcreateddt order by (select null)) rn2
  from Table1
) t  
where t.rn2 = 1

参见demo
结果:

>   ID | Ref_No | MsgCreatedDt            | Remarks  
> ---: | :----- | :---------------------- | :--------
> 1    | Ref1   | 2020-03-22 17:39:00.000 | null     
> 2    | Ref1   | 2020-03-22 17:42:00.000 | Duplicate
> 3    | Ref1   | 2020-03-22 18:10:00.000 | Duplicate
> 4    | Ref2   | 2020-03-22 16:11:00.000 | null 

比双行号方法稍微简单:

  insert into Table2
  select
    min(id),
    ref_no,
    msgcreateddt,
    case when msgcreateddt > min(msgcreateddt) over (partition by ref_no) then 'Duplicate' end 
  from Table1
  group by ref_no, msgcreateddt

之所以有效,是因为 window 函数是在 group by 之后完成的; group by 删除具有完全重复日期的行,然后 window 函数(min(msgcreateddt) over(partition by ref_no) - 它计算出每个 ref_no 的最小日期)用于计算当前行的 msgcreateddt 大于最小日期