環境:SQL Server 2012如何根據同一表中的現有記錄更新字段
我需要維護查詢幫助來更新下圖中的4個空值。我也有一個sqlfiddle to look at (edited)
在這個例子中,第一個SideSort null應該是7.0,因爲有一個現有的SideId爲1,它有一個值要使用。第二個應該是8.0。
這同樣適用於TopSort,但是,如果沒有一個現有的TopId或SideId只是默認爲1
環境:SQL Server 2012如何根據同一表中的現有記錄更新字段
我需要維護查詢幫助來更新下圖中的4個空值。我也有一個sqlfiddle to look at (edited)
在這個例子中,第一個SideSort null應該是7.0,因爲有一個現有的SideId爲1,它有一個值要使用。第二個應該是8.0。
這同樣適用於TopSort,但是,如果沒有一個現有的TopId或SideId只是默認爲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
由於同一個topSort
和sideSort
有多個值,我只是在內部查詢中返回top 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
你試過了嗎?或者使存儲過程來做到這一點? – ohmusama
在你的sqlfiddle中有一個小錯誤,第6行有sideid 1,應該是be2(搜索爲什麼連接不起作用) – ARA
謝謝,我改變了它並更新了鏈接。 – Rod