如何在SQLServer中比较前一行的日期和更新条目

ubby3x7f  于 2021-08-13  发布在  Java
关注(0)|答案(2)|浏览(408)

我一直在想办法通过比较前几行的日期来更新一些条目。
以下是我愿意更新的表中存储的日期示例:

  1. ContractId PartnerId DocumentState DealsDate ActualCloseDate
  2. -------------------------------------------------------------------
  3. 119577922 1450216 38 2016-04-21 2017-08-01
  4. 222138372 1450216 38 2017-11-22 2019-04-01
  5. 223328932 1450216 38 2018-07-30 2018-11-19
  6. 224263667 1450216 38 2019-01-15 2019-04-19
  7. 225286013 1450216 38 2019-06-21 2019-07-19
  8. 225704493 1450216 38 2019-08-30 2019-12-11

目的是改变 DocumentState 到36岁 ContractId 是为了什么 ActualCloseDate 之前的任何条目的 DealsDate .
输出应如下所示:

  1. ContractId PartnerId DocumentState DealsDate ActualCloseDate
  2. -------------------------------------------------------------------
  3. 119577922 1450216 38 2016-04-21 2017-08-01
  4. 222138372 1450216 38 2017-11-22 2019-04-01
  5. 223328932 1450216 36 2018-07-30 2018-11-19
  6. 224263667 1450216 36 2019-01-15 2019-04-19
  7. 225286013 1450216 38 2019-06-21 2019-07-19
  8. 225704493 1450216 38 2019-08-30 2019-12-11

下面是将数据插入临时表的代码。

  1. create table #Test
  2. (
  3. ContractId int,
  4. PartnerId int,
  5. DocumentState int,
  6. DeasDate datetime,
  7. ActualCloseDate datetime
  8. )
  9. insert into #Test (ContractId, PartnerId, DocumentState, DealsDate, ActualCloseDate) values (119577922, 1450216, 38, '2016-04-21', 2017-08-01')
  10. insert into #Test (ContractId, PartnerId, DocumentState, DealsDate, ActualCloseDate) values (222138372, 1450216, 38, '2017-11-22', 2019-04-01')
  11. insert into #Test (ContractId, PartnerId, DocumentState, DealsDate, ActualCloseDate) values (223328932, 1450216, 38, '2018-07-30', 2018-11-19')
  12. insert into #Test (ContractId, PartnerId, DocumentState, DealsDate, ActualCloseDate) values (224263667, 1450216, 38, '2019-01-15', 2019-04-19')
  13. insert into #Test (ContractId, PartnerId, DocumentState, DealsDate, ActualCloseDate) values (225286013, 1450216, 38, '2019-06-21', 2019-07-19')
  14. insert into #Test (ContractId, PartnerId, DocumentState, DealsDate, ActualCloseDate) values (225704493, 1450216, 38, '2019-08-30', 2019-12-11')

提前谢谢!
干杯,

dm7nw8vv

dm7nw8vv1#

我认为可更新的cte可以满足您的需求:

  1. with toupdate as (
  2. select t.*,
  3. max(ActualCloseDate) over (partition by PartnerId
  4. order by dealsDate
  5. rows between unbounded preceding and 1 preceding
  6. ) as prev_max_acd
  7. from #test t
  8. )
  9. update toupdate
  10. set documentstate = 36
  11. where prev_max_acd > dealsdate;

这是一把小提琴

ddarikpa

ddarikpa2#

你可以试试这个

  1. update Test set DocumentState = 36
  2. where exists (
  3. select * from Test inrTest
  4. where inrTest.ContractId < Test.ContractId
  5. and inrTest.ActualCloseDate > Test.DealsDate
  6. )

如果订单不在“contracid”上,那么只需将contract id条件更改为您要订购的列

相关问题