Sql server SQL-仅当未发生更新时,才尝试在找到记录时更新字段

Sql server SQL-仅当未发生更新时,才尝试在找到记录时更新字段,sql-server,Sql Server,仅当状态= “D”并且没有其他具有相同事务id且状态为“D”的记录,如果“D”记录是所选记录,我们还需要第一个“D”记录的日期时间 DECLARE decision TABLE ( transaction_id NCHAR(1), event_id INT, status NCHAR(1) NULL, statud_date datetime ) INSERT decision VALUES ( '1' , 1 , 'D', '2011-01-01'),

仅当状态= “D”并且没有其他具有相同事务id且状态为“D”的记录,如果“D”记录是所选记录,我们还需要第一个“D”记录的日期时间

DECLARE decision TABLE (
transaction_id NCHAR(1),      
event_id INT,      
status NCHAR(1) NULL,
statud_date datetime
)  

INSERT decision VALUES     
( '1' , 1 , 'D', '2011-01-01'),     
( '1' , 2 , 'D', '2011-01-01'),     
( '1' , 3 , 'A', '2011-01-01'),     
( '2' , 1 , 'D', '2011-05-01'),     
( '2' , 2 , 'D', '2011-05-02'),  
( '2' , 3 , 'D', '2011-05-03'),     
( '3' , 1 , 'D', '2011-05-05'),     
( '3' , 2 , 'A', '2011-05-06'),     
( '3' , 3 , 'C', '2011-05-06'),
( '4' , 1 , 'D', '2011-10-01')


DECLARE status TABLE (
transaction_id NCHAR(1),      
default_dt datetime
)

INSERT load VALUES     
( '1' , NULL ),     
( '2' , NULL ),     
( '3' , NULL ),
( '4' , NULL )     
希望得到这个结果:

1   NULL
2   2011-05-01
3   NULL
4   2011-10-01

如果我理解你的意思,你可以看看这个:

DECLARE @decision TABLE (
transaction_id NCHAR(1),      
event_id INT,      
status NCHAR(1) NULL,
status_date datetime
)  

INSERT @decision VALUES     
( '1' , 1 , 'D', '2011-01-01'),     
( '1' , 2 , 'D', '2011-01-01'),     
( '1' , 3 , 'A', '2011-01-01'),     
( '2' , 1 , 'D', '2011-05-01'),     
( '2' , 2 , 'D', '2011-05-02'),  
( '2' , 3 , 'D', '2011-05-03'),     
( '3' , 1 , 'D', '2011-05-05'),     
( '3' , 2 , 'A', '2011-05-06'),     
( '3' , 3 , 'C', '2011-05-06'),
( '4' , 1 , 'D', '2011-10-01')


DECLARE @status TABLE (
transaction_id NCHAR(1),      
default_dt datetime
)

INSERT @status VALUES     
( '1' , NULL ),     
( '2' , NULL ),     
( '3' , NULL ),
( '4' , NULL )


--1st approach
UPDATE S
SET S.default_dt=D.status_date
FROM @status S
     JOIN (SELECT transaction_id,MIN(status_date) status_date, COUNT(*) cnt
           FROM @decision
           WHERE [status]='D'
           GROUP BY transaction_id) D ON S.transaction_id=D.transaction_id
WHERE S.transaction_id NOT IN (SELECT transaction_id FROM @decision WHERE [status]<>'D')

SELECT * FROM @status       

--2nd approach  
UPDATE S
SET S.default_dt=D.status_date
FROM @status S
     JOIN (SELECT transaction_id,MIN(status_date) status_date, COUNT(*) cnt
           FROM @decision
           WHERE [status]='D'
           GROUP BY transaction_id) D ON S.transaction_id=D.transaction_id
     JOIN (SELECT transaction_id, COUNT(*) cnt
           FROM @decision
           GROUP BY transaction_id) D2 ON S.transaction_id=D2.transaction_id AND D.cnt=D2.cnt

SELECT * FROM @status   

非常感谢。我发现我的解决方案没有正常工作,这与您的第一种方法不同,因为您是如何实现where子句的。这完全有道理!我很高兴能帮上忙。感谢您的回复。测试脚本+1。下层选民,你为什么不解释你的-1的原因?