避免自我加入和更新

时间:2016-02-15 12:21:53

标签: sql-server sql-server-2012

我有这样的数据集

rowno   kc      id      BStart      bFinish     Perioddate  
310     48      307861  2015-01-20  2015-01-22  2015-10-10
310     48      307861  2015-01-20  2015-01-22  2016-01-16
310     48      307861  2015-01-20  2015-01-22  2016-04-23
310     48      307861  2015-01-20  2015-01-22  2016-07-30
310     48      307861  2015-01-20  2015-01-22  2016-11-05
310     48      307861  2015-01-20  2015-01-22  2019-01-13
310     48      307861  2015-01-20  2015-01-22  NULL


UPDATE m2        
  SET         
  BStart = (CASE WHEN m.BStart <= m2.BFinish and m2.BFinish <= m.Perioddate         
        THEN DATEADD(dd, 1,m.periodDate)         
    WHEN m.BStart <= m2.BFinish And m2.BFinish > m2.periodDate And m.BStart <= m.PeriodDate         
        THEN DATEADD(dd, 1,m.periodDate)        
  ELSE m.BStart END)    
  FROM #result56 AS m         
  INNER JOIN #result56 AS m2        
  ON m.ROWNO = m2.ROWNO - 1 
  and m.Kc = m2.Kc;

我从这个

的更新语句中获得输出
rowno   kc      id      BStart      bFinish     Perioddate 
310     48      307861  2015-01-20  2015-01-22  2015-10-10
310     48      307861  2015-10-11  2015-01-22  2016-01-16
310     48      307861  2016-01-17  2015-01-22  2016-04-23
310     48      307861  2016-04-24  2015-01-22  2016-07-30
310     48      307861  2016-07-31  2015-01-22  2016-11-05
310     48      307861  2016-11-06  2015-01-22  2019-01-13
310     48      307861  2019-01-14  2015-01-22  NULL

如何仅使用选择不使用更新而不使用自联接

来获得结果

1 个答案:

答案 0 :(得分:-1)

如果只是需要'之前的行'(m.ROWNO = m2.ROWNO - 1),那么我建议使用LEAD; 但是既然你也需要m.Kc = m2.Kc我没有看到你想要实现这个目标而没有自我加入是诚实的。