需要有关在sql server中更新activity_date的帮助

时间:2018-01-03 09:31:21

标签: sql sql-server

嗨,我有一张桌子,如下所示。对于包含activity_type 37213770/3771

的所有individual_ID,我需要将activity_type 3721的日期更新为activity_type 3770 or 3771的活动日期
[IND_ID]   [ACTIVITY_TYPE]   [ACTIVITY_DATE]
   100           3770           12/12/2014
   100           3721              Null
   103           3771          21/06/2017
   103           3721              Null
   122           3770          07/07/2017
   122           3721              Null

以下是我的以下查询无效

declare 
@actiondate DATETIME,
@ind_ref int

SET @actiondate = (select ACTION_DATE  from ACTIVITY_LOG where activity_type in (3770,3771) and INDIVIDUAL_REF=@ind_ref) 

UPDATE ACTIVITY_LOG 
SET ACTION_DATE= (
      CASE 
      WHEN ACTIVITY_TYPE='3721' AND ACTION_DATE IS NULL AND ACTIVITY_LOG.INDIVIDUAL_REF=@ind_ref 
      THEN @actiondate
      ELSE ACTION_DATE
      END) 
FROM ACTIVITY_LOG

2 个答案:

答案 0 :(得分:3)

使用UPDATE(显然)自我加入:

update x1
set x1.ACTIVITY_DATE = x2.ACTIVITY_DATE

from MyTable x1
inner join MyTable x2
  on x1.IND_ID =x2.IND_ID
  and x1.ACTIVITY_TYPE <> x2.ACTIVITY_TYPE
where x1.ACTIVITY_DATE is null
and x2.ACTIVITY_DATE is not null

答案 1 :(得分:1)

使用自联接进行更新是一种方式。

另一种方法是将列设置为自联接表的前1个子查询。

例如:

UPDATE t 
SET [ACTIVITY_DATE] = (
     SELECT TOP 1 t2.[ACTIVITY_DATE] 
     FROM YourTable t2
     WHERE t2.[ACTIVITY_TYPE] IN (3770, 3771)
       AND t2.[ACTIVITY_DATE] IS NOT NULL
       AND t2.[IND_ID] = t.[IND_ID]
     ORDER BY t2.[ACTIVITY_DATE] DESC
    )
FROM YourTable t
WHERE t.[ACTIVITY_TYPE] = 3721
  AND t.[ACTIVITY_DATE] IS NULL;

对于相同的IND_ID,ORDER BY只是存在多个3770和/或3771。

使用自联接它会是这样的:

UPDATE t
SET [ACTIVITY_DATE] = t2.[ACTIVITY_DATE]
FROM YourTable t
JOIN YourTable t2
  ON ( t2.[IND_ID] = t.[IND_ID]
   AND t2.[ACTIVITY_TYPE] IN (3770, 3771)
   AND t2.[ACTIVITY_DATE] IS NOT NULL
  )
WHERE t.[ACTIVITY_TYPE] = 3721
  AND t.[ACTIVITY_DATE] IS NULL;

哪个应该更快,但是你不能使用ORDER BY。