SQL使用另一行中的值更新多行

时间:2018-06-23 11:55:56

标签: sql sql-server sql-update

Id  JobId   Code    DateAdded   

1   100     FR1F    2018-06-22 14:19:57.807

2   100     W2OO    2018-06-22 16:52:53.160 

3   101     FR1F    2018-06-22 14:19:57.237

4   101     W2OO    2018-06-22 16:52:53.160 

5   102     FR1F    2018-06-22 14:19:48.020 

6   102     W2OO    2018-06-22 16:52:53.160

嗨,我有一个查询的结果,上面有一部分数据示例描述了查询的一部分。

查询如下:

SELECT 
        T1.Id
    ,   T2.JobId
    ,   T3.Code
    ,   T1.DateAdded
  FROM T1 
  INNER JOIN T2 ON T1.JobId = T2.JobId 
  INNER JOIN T3 ON T1.T3Id = T3.Id
  WHERE T3.Code = 'W2OO' OR T3.Code = 'FR1F'

我需要用Code ='W200'的行中的DateAdded值更新Code ='FR1F'的行的DateAdded值

希望对具有远远超过我的SQL技能的人来说,这是一个简单的任务!感谢收到任何帮助。

预先感谢

编辑:

以下是我根据您的回答戈登所作的解释,但它更改了0行

BEGIN TRAN

UPDATE JR
    SET DateAdded = DATEADD(MS, -3, JRFrom.DateAdded)
    FROM [OPC].[dbo].[JobRFI] JR 
    INNER JOIN [OPC].[dbo].[Job] J ON JR.JobId = J.JobId AND ProjectID = '123'
    INNER JOIN [OPC].[dbo].[RFI] R ON JR.RFIId = R.RFIId
    JOIN [OPC].[dbo].[JobRFI] JRFrom ON JR.Jobid = JRFrom.Jobid 
        AND R.RFICode = 'FR1F' 
        AND R.RFICode = 'W200'


SELECT 
        JR.JobRFIId
    ,   J.JobId
    ,   R.RFICode
    ,   R.Display
    ,   JR.DateAdded
    ,   DATEADD(MS, -3, JR.DateAdded)
  FROM [OPC].[dbo].[JobRFI] JR
  INNER JOIN [OPC].[dbo].[Job] J ON JR.JobId = J.JobId AND ProjectID = '123'
  INNER JOIN [OPC].[dbo].[RFI] R ON JR.RFIId = R.RFIId
  WHERE R.RFICode = 'W2OO' OR R.RFICode = 'FR1F'

ROLLBACK TRAN

再次感谢您的关注!

2 个答案:

答案 0 :(得分:1)

大概是您想要的:

update t
    set dateAdded = tfrom.dateAdded
    from t join
         t tfrom
         on t.jobid = tfrom.jobid and
            t.Code = 'FR1F' and
            tfrom.Code = 'W200' ;

答案 1 :(得分:1)

使用相关子查询:

update t
set dateadded = (
      select dateadded
      from t tf
      where t.jobid = tf.jobid
      and tf.code = 'W200')
where t.code = 'FR1F'