我有两张这样的表:
Application
ApplicationID ApplicationDesc VersionNo
1 APP1 1
2 APP2 1
3 APP3 1
4 APP1 2
5 APP2 2
6 APP1 3
Order
OrderID ApplicationID OrderDescription
1 1 Belongs to APP1 version 1
2 4 Belongs to APP1 version 2
3 6 Belongs to APP1 version 3
我想使用相应应用程序的最新版本的ApplicationID更新表Order中的列ApplicationID。
我希望数据看起来像这样:
Order
OrderID ApplicationID OrderDescription
1 6 Belongs to APP1 version 1
2 6 Belongs to APP1 version 2
3 6 Belongs to APP1 version 3
我如何做到这一点?请帮忙。
答案 0 :(得分:2)
您可以使用公用表表达式查找最新的ApplicationID,然后将更新语句加入CTE:
;WITH cteNewest(ApplicationID, NewestApplicationID)
AS(
SELECT
ApplicationID
,MAX(ApplicationID) OVER(PARTITION BY ApplicationDesc)
FROM Application
)
UPDATE o
SET o.ApplicationID = new.NewestApplicationID
FROM [Order] o
JOIN cteNewest new
ON o.ApplicationID = new.ApplicationID;