2014-03-25 35 views
0

這是一個MS-SQLSQL更新其他行最近一個日期行

有許多行數據重複,其中一些獲得最新的更新,一些沒有。 我想用那些獲取最新信息來更新這些舊數據。

from: 
    orderNum  itemID   orderTime      desc 
    7247168   101   2013-08-11 09:51:39.20    desc_101_cc 
    102594   101   2012-09-26 21:17:50.44    desc_101_aaa 
    631595   101   2014-03-11 19:51:29.40    desc_101_ddd 
    1157428   235   2014-03-01 10:16:42.43    desc_235_8 
    7212306   235   2014-03-14 11:26:51.29    desc_235_2 
    100611   235   2014-03-21 20:23:43.03    desc_235_2 

要:

orderNum  itemID   orderTime      desc 
7247168   101   2013-08-11 09:51:39.20    desc_101_ddd 
102594   101   2012-09-26 21:17:50.44    desc_101_ddd 
631595   101   2014-03-11 19:51:29.40    desc_101_ddd 
1157428   235   2014-03-01 10:16:42.43    desc_235_2 
7212306   235   2014-03-14 11:26:51.29    desc_235_2 
100611   235   2014-03-21 20:23:43.03    desc_235_2 

我想用max(orderTime)獲得的desc 的最新版本,然後用它來更新其他desc

這意味着我喜歡用orderTime來告訴哪個desc是最新的 然後更新其他desc

唯一列需要更新的是desc

請幫我這個SQL

+1

你如何決定OLD和新?通過orderTime?你想通過新的itemID更新舊的itemID?請提供更多的細節。 – AK47

+0

更詳細地描述你的問題。我懷疑是否有人會閱讀這些表格來找出差異。並給sql創建你的表。 –

+0

肯定是訂單時間,只是爲了更新desc –

回答

1

如果您使用的是SQL Server 2012中,你可以用last_value做到這一點:

with toupdate as (
     select t.*, 
      last_value("desc") over (partition by itemID order by orderTime) as lastdesc 
     from table t 
) 
update toupdate 
    set "desc" = lastdesc; 

如果您沒有使用SQL Server 2012中,你的模擬這種與相關子查詢:

with toupdate as (
     select t.*, 
      (select top 1 "desc" 
       from table t2 
       where t2.itemId = t.itemId 
       order by orderTime desc 
      ) as lastdesc 
     from table t 
) 
update toupdate 
    set "desc" = lastdesc; 
1

像這樣的東西(不會在SQL Server 2000中或更早版本)?不要在生產桌上試試這個;製作一個臨時副本表來嘗試它。

;WITH MaxT AS (
    SELECT 
     itemID 
     ,maxOrderTime = MAX(orderTime) 
    FROM 
     myTable 
    ), 
MaxTDesc AS (
    SELECT 
     itemID 
     ,desc 
    FROM 
     myTable MaxTDesc 
     ,MaxT 
    WHERE 
     MaxTDesc.ItemID = MaxT.ItemID 
     AND MaxTDesc.orderTime = MaxT.maxOrderTime 
    ) 
UPDATE 
    mt 
SET 
    mt.desc = MaxTDesc.desc 
FROM 
    myTable mt, MaxT 
WHERE 
    mt.itemID = MaxTDesc.itemID 
+1

偉大的建議,請指點。 :) – paqogomez

0

試試這個......我使用ROW_NUMBER()來挑選最新更新的記錄,然後爲其他人設置desc列

WITH CTE 
AS (
    SELECT * 
     , ROW_NUMBER() OVER (partition by itemid ORDER BY ordertime desc) ROWNUM 
    FROM Your_table_name  
    ) 
UPDATE A 
SET desc = CTE.desc 
FROM Your_table_name A 
INNER JOIN CTE ON A.itemid = CTE.itemid 
WHERE CTE.ROWNUM=1