根据另一个 table 的有序值更新列

Update a column based on ordered values from another table

我需要更新 table 中一个名为 AccountBase 的标志,相关时 table SoldItems 具有相同的 uniqueidentifier,但困难的部分是,我需要找到最新售出的产品并比较它SellDatetime 也包含当前时间。当最新的产品在 6 年内销售时我想将标志设置为 1,否则为 0。

AccountBase和SoldItems之间有1:N连接,多个商品可以卖到一个账户,所以我需要在SoldItems中按SellDatetime订购。

这是我的尝试,但设置不正确,但内部查询存在 returns 正确的值:

UPDATE acc 
   SET acc.SoldInLastSixYears = CASE WHEN DATEDIFF(DAY, hk.SellDatetime, GETDATE())/ 365.2425 >= 6 THEN 0
            ELSE 1
            END
FROM [AccountBase] acc INNER JOIN SoldItems hk ON acc.AccountId=hk.Owner
where EXISTS(select top(1) SellDatetime From SoldItems where 
SellDatetime is not null AND Owner is not null 
AND Owner=acc.AccountId   order by SellDatetime desc) 

当我尝试使用内部查询值时出现错误,我 sql 无法识别 'hk':

UPDATE acc 
   SET acc.SoldInLastSixYears = CASE WHEN DATEDIFF(DAY, hk.SellDatetime, GETDATE())/ 365.2425 >= 6 THEN 0
            ELSE 1
            END
FROM [AccountBase] acc 
where EXISTS(select top(1) SellDatetime From SoldItems hk where 
SellDatetime is not null AND Owner is not null 
AND Owner=acc.AccountId   order by SellDatetime desc) 

请大神帮帮我,应该怎么做?

据我了解你的问题,你想要的是最新的销售记录。

您可以使用 NOT EXISTS 的相关查询,如下所示:

UPDATE acc 
   SET acc.SoldInLastSixYears 
       = CASE WHEN DATEDIFF(DAY, hk.SellDatetime, GETDATE())/ 365.2425 >= 6 THEN 0
              ELSE 1
         END
FROM [AccountBase] acc INNER JOIN SoldItems hk ON acc.AccountId=hk.Owner
where NOT EXISTS(select 1 From SoldItems s where 
s.Owner=acc.AccountId and s.SellDatetime > hk.SellDatetime) 

我认为您的查询过于复杂。

UPDATE acc 
   SET acc.SoldInLastSixYears = (CASE WHEN DATEDIFF(DAY, hk.SellDatetime, GETDATE())/ 365.2425 >= 6
                                     THEN 0 ELSE 1
                                 END)
FROM AccountBase acc INNER JOIN
     (SELECT hk.Owner, MAX(SellDatetime) as max_SellDateTime
      FROM SoldItems hk
      GROUP BY hk.Owner
     ) hk
     ON acc.AccountId = hk.Owner;

我也不建议通过猜测日期来进行年份比较。而是使用逻辑:

UPDATE acc 
   SET SoldInLastSixYears = (CASE WHEN hk.SellDatetime <= DATEADD(YEAR, -6, GETDATE()) 
                                  THEN 0 ELSE 1
                             END)
FROM AccountBase acc INNER JOIN
     (SELECT hk.Owner, MAX(SellDatetime) as max_SellDateTime
      FROM SoldItems hk
      GROUP BY hk.Owner
     ) hk
     ON acc.AccountId = hk.Owner;