2011-10-12 60 views
0

僅當狀態= 'D'且沒有其他記錄具有相同記錄時,纔會使用以下數據並在狀態表中填充日期時間transaction_id的狀態爲<>'D',如果'D'記錄是選定的記錄,我們也需要第一個'D'記錄的日期時間。SQL - 試圖在發現記錄時更新字段,但只有在未發生更新時纔會更新字段

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 
+0

+1的測試腳本。 Downvoters,你爲什麼不解釋你的-1的原因? –

回答

2

如果我理解你正確TNAN你可以看看這個:

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

謝謝!我發現我的解決方案(無法正常工作)與您的第一種方法不同之處在於您如何實現where子句。這是完全合理的! –

+0

我很高興能幫上忙。感謝您的答覆。 –

相關問題