我有三个场景要实现。
Case 1- When IM.Code=IME.Code and IM.Effective_st_dt=IME.effective_st_dt and IM.Effective_end_dt =IME.Effective-end_date操作-在本例中,我需要用currentMrp和currentCp更新IM。
Case 2- When IM.Code=IME.Code and IM.Effective_st_dt!=IME.effective_st_dt and IM.Effective_end_dt =IME.Effective-end_date)从IM中选择最近的Effective_st_dt记录,并使用(IME.Effective_st_dt)-1更新Effective_end_date
)然后从IME插入一个具有新effective_st_dt的新记录,这个记录lastMRP和lastcp是在1中更新的前一个记录的当前has和Currentcp。
案例3-当IM.Code=IME.Code和IM.Effective_st_dt!=IME.effective_st_dt和IM.Effective_end_dt!= Case .有效-结束日期
)从IM中选择最近的Effective_st_dt记录,并使用(IME.Effective_st_dt)-1更新Effective_end_date
)然后从IME插入一个具有新effective_st_dt的新记录,这个记录lastMRP和lastcp是在1中更新的前一个记录的当前has和Currentcp。
这是我的表的脚本
Create Table IM
(
ID int idenetity (1,1)
,Code varchar(100)
,CurrentMrp float
,CurrentCP float
,lastMrp float
,lastCp float
, effective_st_dt date
,effective_end_dt date
)
Create table IME
(
Code varchar(100)
,CurrentMrp float
,CurrentCP float
,Effective_st_dt date
,Effective_end_dt date
)
insert into IM (code, currentMrp, currentCp, lastMRP, lastCP, effective_st_dt, effective_end_dt)
Select
'CA123', 10.12, 5.0, 8.20, 4, '2014-05-01', '2014-05-31'
union
Select 'CA123',15.0,5.0,10.12,8.20,'2014-06-01','2014-08-31'
union
Select 'CA121',50.0,15.0,45.0,25.0,'2014-04-01','2014-05-31'
union
Select 'CA121',75.0,25.0,50.0,15.0,'2014-06-01','2014-06-30'
union
Select 'CA131',53.0,12.0,35.0,10.0,'2014-05-01','2014-05-31'
union
Select 'CA131',60.0,15.0,53.0,12.0,'2014-06-01','2014-08-31'
Insert into IME (code,effective_st_dt,effective_end_dt)
Select ('CA123',20.0,5.0,'2014-06-01','2014-08-31')
union
Select ('CA123',25.0,6.0,'2014-06-20','2014-08-31')
union
Select ('CA123',35.0,7.0,'2014-07-15','2015-03-31')请帮我解决这个问题
感谢您的帮助。
发布于 2015-03-29 09:43:13
在这种特殊情况下,最好使用左联接而不是内部联接,否则不会给出正确的结果。
https://stackoverflow.com/questions/24464799
复制相似问题