2013-11-24 32 views
2

環境:SQL Server 2012如何根據同一表中的現有記錄更新字段

我需要維護查詢幫助來更新下圖中的4個空值。我也有一個sqlfiddle to look at (edited)

在這個例子中,第一個SideSort null應該是7.0,因爲有一個現有的SideId爲1,它有一個值要使用。第二個應該是8.0。

這同樣適用於TopSort,但是,如果沒有一個現有的TopId或SideId只是默認爲1

enter image description here

+0

你試過了嗎?或者使存儲過程來做到這一點? – ohmusama

+0

在你的sqlfiddle中有一個小錯誤,第6行有sideid 1,應該是be2(搜索爲什麼連接不起作用) – ARA

+0

謝謝,我改變了它並更新了鏈接。 – Rod

回答

1

你可以這樣這樣說:

update Tracker 
set topSort = (select top 1 isnull(topSort, 1) from Tracker T where T.topId = Tracker.topId) 
where topSort is null 

update Tracker 
set sideSort = (select top 1 isnull(sideSort, 1) from Tracker T where T.sideId = Tracker.sideId) 
where sideSort is null 

由於同一個topSortsideSort有多個值,我只是在內部查詢中返回top 1,但您可能希望將其替換爲僅返回一條記錄的其他值。

1

如果SideId不是要使用的SideSort記錄的id,則連接在同一個SideId上完成。 的更新是:

update t1 
set t1.sidesort = coalesce(t2.sidesort,1) 
FROM Tracker t1 
    left join Tracker t2 
      on t2.SideId = t1.sideid 
      and t2.SideId is not null 
where t1.sidesort is null 

update t1 
set t1.topsort = coalesce(t2.topsort,1) 
FROM Tracker t1 
    left join Tracker t2 
      on t2.topid = t1.topid 
      and t2.topId is not null 
where t1.topsort is null 
+0

應該t2.sideId = t1.sideId – Rod

+0

我覺得這是使用的id。我糾正它 – ARA

相關問題