SQL Server:基于类似列的更新列

时间:2013-09-12 15:49:47

标签: sql-server

我们正在使用SQL Server 2008,这是表的一个示例。我正在尝试清理(然后将删除重复项),prev_date列在item#相同时不同。我想用max(prev_date)值更新两个记录。我很难找到如何使用单个语句为多个记录执行此操作

key                     item(int)             prev_date(int)
--------------------------------------------------------------------
15086                           1163            20121023
16289                           1163            20130121
15087                           1164            20121024
16290                           1164            20130120
15088                           1165            20121029
16291                           1165            20130120

3 个答案:

答案 0 :(得分:2)

update a set a.date=b.date from table_1 as a 
inner join 
(select *,row_number() over(partition by item order by date desc)as rownum from table_1  
)b 
on a.item=b.item and b.rownum=1

答案 1 :(得分:1)

CTE提供了一个干净的SQL

;with cte_max(item, maxdate) as (
 select item, max(prev_date) from t
 group by item
)
update t
    set prev_date = m.maxdate
  from t
    inner join cte_max m on t.item = m.item 
 where t.prev_date <> m.maxdate

答案 2 :(得分:0)

对于这些类型的更新,我喜欢使用可更新的CTE:

with toupdate (
      select t.*, max(prev_date) over (partition by item) as new_prev_date
      from t
     )
update toupdate
    set prev_date = new_prev_date
    where prev_date <> new_prev_date;  -- optional `where` clause

还有其他方法。标准SQL将是:

update t
    set prev_date = (select max(prev_date) from t t2 where t2.item = t.item);