开发者

SQL - Attempting to update field if record found but only if an update has not occurred

Looking to use the following data and开发者_JS百科 populate the datetime in status table only if status = 'D' and there is NOT another record with the same transaction_id that has a status <> 'D', if the 'D' record is the selected record, we also want the datetime of the first 'D' record.

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 )     

Looking to get this result:

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


If I understand you correct tnan you can look at this:

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   
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜