配偶表配偶 ID
SpousePreviousAddressesTable PreviousAddressID , SpouseID , FromDate, AddressTypeID
我现在所拥有的是更新整个表的最新数据并分配最新数据,而不管 SpouseID 的 AddressTypeID = 1
我想为 SpousePreviousAddresses 表中的每个唯一 SpouseID 分配最新的 SpousePreviousAddress.AddressTypeID = 1。
UPDATE spa
SET spa.AddressTypeID = 1
FROM SpousePreviousAddresses AS spa INNER JOIN Spouses ON spa.SpouseID = Spouses.SpouseID,
(SELECT TOP 1 SpousePreviousAddresses.* FROM SpousePreviousAddresses
INNER JOIN Spouses AS s ON SpousePreviousAddresses.SpouseID = s.SpouseID
WHERE SpousePreviousAddresses.CountryID = 181 ORDER BY SpousePreviousAddresses.FromDate DESC) as us
WHERE spa.PreviousAddressID = us.PreviousAddressID
我想我需要一个 group by,但我的 sql 并不是那么热。谢谢。
正在运行的更新
我之前找到了解决方案是错误的。以下是我要使用的解决方案
WITH result AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) AS rowNumber, *
FROM SpousePreviousAddresses
WHERE CountryID = 181
)
UPDATE result
SET AddressTypeID = 1
FROM result WHERE rowNumber = 1