根据ID查找记录,比较日期并用最早的日期更新记录

时间:2019-10-10 11:51:55

标签: sql sql-server

我有一个表,我们称它为UserTable。

enter image description here

我想做的是:

  • 找到重复的用户ID
  • 比较StartDate并通过填写EndDate(当前日期减1)来更新具有最旧StartDate的记录
  • 对表中的所有重复记录执行此操作

最终结果应如下:

enter image description here

我将其归结为:

UPDATE UserTable
    SET EndDate = GETDATE()-1
WHERE EndDate IS NULL AND StartDate < (GETDATE()) AND
(UserID) in (
  select UserID 
  from   UserTable
  group  by UserID
  having count(*) > 1)

我唯一不知道的事情是如何仅更新具有最旧StartDate的那个。根据上面的代码,找到的所有记录都会更新。

1 个答案:

答案 0 :(得分:0)

我不确定为什么只想更新一条记录。但是,一种方便的方法是使用可更新的CTE:

with toupdate as (
      select ut.*,
             row_number() over (partition by userid order by startdate) as seqnum
      from UserTable ut
     )
update toupdate
    set EndDate = dateadd(day, -1, getdate())
    where seqnum = 1;