在Inner Join中不等于

时间:2014-06-28 07:51:09

标签: join sql-server-2012 subquery correlated-subquery

我有3个方案要实施。

案例1-当IM.Code = IME.Code和IM.Effective_st_dt = IME.effective_st_dt和IM.Effective_end_dt = IME.Effective-end_date

动作 - 在这种情况下,我需要使用currentMrp和currentCp更新IM。

案例2-当IM.Code = IME.Code和IM.Effective_st_dt!= IME.effective_st_dt和IM.Effective_end_dt = IME.Effective-end_date

动作 - 1.)从IM中选择最近的Effective_st_dt记录,并使用(IME.Effective_st_dt)-1更新Effective_end_date

2.)然后从IME插入一条新记录,其中包含新的effective_st_dt此记录lastMRP和lastcp是上一条记录的currentmrp和Currentcp,在1中更新

案例3-当IM.Code = IME.Code和IM.Effective_st_dt!= IME.effective_st_dt和IM.Effective_end_dt!= IME.Effective-end_date

动作 - 1.)从IM中选择最近的Effective_st_dt记录,并使用(IME.Effective_st_dt)-1更新Effective_end_date

2.)然后从IME插入一条新记录,其中包含新的effective_st_dt此记录lastMRP和lastcp是上一条记录的currentmrp和Currentcp,在1中更新

这是我的表格的脚本

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')

请帮我解决这个问题

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

在这种特殊情况下你更好地使用左连接而不是内连接,否则不等于不会给你正确的结果。