更新相应行值的日期

时间:2017-04-26 17:08:55

标签: sql sql-server

我正在尝试在下面的数据集中为给定的开始日期(下面的案例中为4/20)创建新的日期列,其中相应的发票号码的请求日期小于开始日期(4/20)。我尝试设置一个计数器,其中包含发票编号,但它没有用。

有人可以帮助我吗?

invoice#    RequestDate Newdate
123          4/18/2017  4/20/2017
123          4/16/2017  4/21/2017
123          4/17/2017  4/22/2017
126          4/15/2017  4/20/2017
126          4/16/2017  4/21/2017
126          4/17/2017  4/22/2017
126          4/18/2017  4/23/2017
126          4/19/2017  4/24/2017
131          4/13/2017  4/20/2017
131          4/14/2017  4/21/2017
131          4/15/2017  4/22/2017
131          4/16/2017  4/23/2017
131          4/17/2017  4/24/2017
131          4/18/2017  4/25/2017
131          4/19/2017  4/26/2017

2 个答案:

答案 0 :(得分:1)

select invoice#,requestdate,
 row_number() over (partition by invoice# order by invoice#) + getdate() -1  as newdate
from t

答案 1 :(得分:1)

首先,让我们确定您要修改的发票。我们在子查询PastInvoices中执行此操作。然后,您可以使用ROW_NUMBER()和PARTITION BY来创建递增日期。

SELECT AllInvoices.invoice,
    RequestDate,
    CASE
        WHEN PastInvoices.invoice IS NOT NULL
        THEN DATEADD(day, (ROW_NUMBER() over (partition by AllInvoices.invoice order by AllInvoices.invoice)) - 1, GETDATE())
        ELSE RequestDate
    END as NewDate
FROM RequestDate as AllInvoices
LEFT OUTER JOIN 
    (select distinct invoice from RequestDate where RequestDate < GETDATE()) as PastInvoices
on AllInvoices.invoice = PastInvoices.invoice