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

时间:2011-10-12 05:20:42

标签: sql-server

仅当status =时,才能使用以下数据并在状态表中填充日期时间 'D'并且没有另一条具有相同transaction_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

1 个答案:

答案 0 :(得分:2)

如果我理解你的正确,你可以看看:

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