2015-10-12 28 views
0

我如何才能刪除重複記錄刪除doublon內加入

update r 
    set Comp = t.Comp 
from [QlikDataWarehouse].[dbo].[Vente]r with (NOLOCK) inner join 
    [QlikDataWarehouse].[dbo].[Budget] t 
    on t.[Code Site] = r.[Code Site] and 
     t.[Code Rayon] = substring(r.[Code Structure],1,4) and 
     t.[Date Time] = convert(date,r.[Date Time]) 
where r.[Date Time] >= '2015-01-01 00:0:00.000'; 
+0

您的問題對我沒有多大意義。爲什麼你想要頂級1,這樣你可以複製?不知道我遵循。如果您試圖刪除您爲什麼要使用更新? –

+1

更新聲明與NOLOCK,至少我不想知道會發生什麼... –

+0

只是讓你知道。在像這樣的更新中使用NOLOCK可能會損壞您的索引,並且自2005年起,語法已被棄用。https://www.mssqltips.com/sqlservertip/3172/avoid-using-nolock-on-sql-server-update-and-刪除語句/ –

回答

0

嘗試是這樣的選擇,從預算只有前1補償:

with topComp as (
    select t.[Code Site], t.[Code Rayon], t.[Date Time], max(t.[Comp]) 
    from [QlikDataWarehouse].[dbo].[Budget] t 
    group by t.[Code Site], t.[Code Rayon], t.[Date Time] 
); 

update r 
    set Comp = t.Comp 
from [QlikDataWarehouse].[dbo].[Vente]r with (NOLOCK) inner join 
    topComp t 
    on t.[Code Site] = r.[Code Site] and 
     t.[Code Rayon] = substring(r.[Code Structure],1,4) and 
     t.[Date Time] = convert(date,r.[Date Time]) 
where r.[Date Time] >= '2015-01-01 00:0:00.000'; 
0

如果我理解正確的話,你有多個匹配budget表,你只需要一個。如果是,則使用cross apply而不是join。例如,爲了獲得最新的記錄:

update r 
    set Comp = t.Comp 
from [QlikDataWarehouse].[dbo].[Vente]r with (NOLOCK) cross apply 
    (select top 1 t.* 
     from [QlikDataWarehouse].[dbo].[Budget] t 
     where t.[Code Site] = r.[Code Site] and 
      t.[Code Rayon] = substring(r.[Code Structure],1,4) and 
      t.[Date Time] = convert(date,r.[Date Time]) 
     order by t.[Date Time] desc 
    ) t 
where r.[Date Time] >= '2015-01-01 00:0:00.000';