1

配偶表配偶 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
4

3 回答 3

5

假设您使用的是 SQLServer 2005(基于您从上一次尝试中得到的错误消息),最直接的方法可能是使用 ROW_NUMBER() 函数和公用表表达式,我认为这可能会做你正在找:

WITH result AS
(
SELECT 
    ROW_NUMBER() OVER (PARTITION BY SpouseID ORDER BY FromDate DESC) as rowNumber,
    * 
FROM 
    SpousePreviousAddresses
)
    UPDATE SpousePreviousAddresses
    SET
        AddressTypeID = 2
    FROM 
        SpousePreviousAddresses spa
            INNER JOIN result r ON spa.SpouseId = r.SpouseId
    WHERE r.rowNumber = 1
            AND spa.PreviousAddressID = r.PreviousAddressID
            AND spa.CountryID = 181

在 SQLServer2005 中,ROW_NUMBER() 函数是最强大的函数之一。它在很多情况下都非常有用。花在学习上的时间会得到很多倍的回报。

CTE 用于简化代码,因为它不需要某种临时表来存储中间结果。

生成的查询应该快速有效。我知道 CTE 中的选择使用 *,这有点矫枉过正,因为我们不需要所有列,但如果有人想查看查询中发生的情况,它可能有助于显示正在发生的事情。

于 2008-11-14T22:10:42.850 回答
1

这是一种方法:

UPDATE spa1
SET spa1.AddressTypeID = 1
FROM SpousePreviousAddresses AS spa1 
  LEFT OUTER JOIN SpousePreviousAddresses AS spa2
    ON (spa1.SpouseID = spa2.SpouseID AND spa1.FromDate < spa2.FromDate)
WHERE spa1.CountryID = 181 AND spa2.SpouseID IS NULL;

换句话说,更新spa1没有其他行spa2存在的具有相同配偶和更大(更近)日期的行。

SpouseID与具有相同SpouseID.

没有必要使用 a GROUP BY,因为连接完成了一种隐式分组。

更新: 我认为你误解了OUTER JOIN. 如果没有与所有spa2连接条件匹配的行,则 的所有列都返回为 NULL。这就是外部连接的工作方式。因此,您可以通过测试来搜索没有匹配行的情况。spa2.*spa1spa2spa2.SpouseID IS NULL

于 2008-11-14T21:52:51.157 回答
0
UPDATE spa SET spa.AddressTypeID = 1 
     WHERE spa.SpouseID IN (
         SELECT DISTINCT s1.SpouseID FROM Spa S1, SpousePreviousAddresses S2
              WHERE s1.SpouseID = s2.SpouseID 
                  AND s2.CountryID = 181 
                  AND s1.PreviousAddressId = s2.PreviousAddressId
              ORDER BY S2.FromDate DESC)

只是一个猜测。

于 2008-11-14T20:49:27.227 回答