首页 > 解决方案 > 如何使用同一组中下一行的数据更新前一条记录

问题描述

我有一组数据,我需要用同一组内下一行中不同列的日期(较早的日期 - 如果存在)更新先前的记录日期列(较早的日期)。

我正在使用 SQL Server 2008 R2,所以我不能使用 LEAD/LAG 函数。

更新前数据:

ArticleId | DiscountStartDate   | DiscountEndDate     | Price
-------------------------------------
1         | 2018-08-10 23:59:59 | null                | 20    
1         | 2018-08-20 10:00:00 | null                | 30    
1         | 2019-01-10 01:00:00 | null                | 20
2         | 2018-11-10 12:00:00 | null                | 10    
1         | 2019-01-15 11:30:00 | null                | 21    
3         | 2018-05-10 12:00:00 | 2019-01-14 14:00:00 | 20    
3         | 2018-07-10 23:00:00 | 2019-01-14 14:00:00 | 10    
3         | 2019-01-10 12:00:00 | 2019-01-14 14:00:00 | 5    
4         | 2018-12-20 00:00:00 | 2019-01-19 14:00:00 | 20


CREATE TABLE [dbo].[ArticleDiscount](
[ArticleID] [int] NULL,
[DiscountStartDate] [datetime] NULL,
[DiscountEndDate] [datetime] NULL,
[Price] [money] NULL
) ON [PRIMARY]
GO
INSERT INTO [dbo].[ArticleDiscount]
       ([ArticleID]
       ,[DiscountStartDate]
       ,[DiscountEndDate]
       ,[Price])
 VALUES
(1, '2018-08-10 23:59:59', null, 20),
(1, '2018-08-20 10:00:00', null, 30),
(1, '2019-01-10 01:00:00', null, 20),
(2, '2018-11-10 12:00:00', null, 10),
(1, '2019-01-15 11:30:00', null, 21),
(3, '2018-05-10 12:00:00', '2019-01-14 14:00:00' , 20),
(3, '2018-07-10 23:00:00', '2019-01-14 14:00:00' , 10),
(3, '2019-01-10 12:00:00', '2019-01-14 14:00:00' , 5),
(4, '2018-12-20 00:00:00', '2019-01-19 14:00:00' , 20) 

更新后数据:

ArticleId | DiscountStartDate   | DiscountEndDate     | Price
-------------------------------------
1         | 2018-08-10 23:59:59 | 2018-08-20 10:00:00 | 20    
1         | 2018-08-20 10:00:00 | 2019-01-10 01:00:00 | 30    
1         | 2019-01-10 01:00:00 | 2019-01-15 11:30:00 | 20    
2         | 2018-11-10 12:00:00 | null                | 10    
1         | 2019-01-15 11:30:00 | null                | 21    
3         | 2018-05-10 12:00:00 | 2018-07-10 23:00:00 | 20    
3         | 2018-07-10 23:00:00 | 2019-01-10 12:00:00 | 10    
3         | 2019-01-10 12:00:00 | 2019-01-14 14:00:00 | 5    
4         | 2018-12-20 00:00:00 | 2019-01-19 14:00:00 | 20

编辑:基本上,如果特定 ArticleId 有较新的条目(DiscountStartDate),我需要关闭该 ArticleID 的先前记录中的 DiscountEndDate。最新记录中的 DiscountEndDate 应保持不变(AtricleId 2,4,因为它们没有其他记录以及 ArticleId 1 和 3 的最新记录),并且记录中是否有空或某个日期无关紧要。

标签: sqlsql-servertsqlsql-server-2008-r2

解决方案


要根据 articleid 更新日期,您可以尝试如下操作。

UPDATE t 
SET    DiscountEndDate = case when d.ddate is null then DiscountEndDate else d.ddate end
FROM   [ArticleDiscount] t 
       CROSS apply (SELECT Min(discountstartdate) ddate 
                    FROM   [ArticleDiscount] t1 
                    WHERE  t1.articleid = t.articleid 
                           AND t1.discountstartdate > t.discountstartdate)d 

在线演示


推荐阅读