sql - 如何使用同一组中下一行的数据更新前一条记录
问题描述
我有一组数据,我需要用同一组内下一行中不同列的日期(较早的日期 - 如果存在)更新先前的记录日期列(较早的日期)。
我正在使用 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 的最新记录),并且记录中是否有空或某个日期无关紧要。
解决方案
要根据 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
推荐阅读
- node.js - 亚马逊 EC2 的 API 网关
- javascript - JavaScript 最长公共子序列
- angular - 如何将登录用户数据以 Angular 8 存储在本地存储中
- javascript - 为什么我的代码告诉我 .draw 不是函数?
- postgresql - 如何修复 Spring Boot Postgres 错误:在或附近出现语法错误:“)”位置:209
- wordpress - Wordpress 类别页面,分页在所有页面中显示相同的帖子
- c# - Unity 脚本 - VideoPlayer 不会暂停
- mongodb - 无法将 filebeat 输出发送到 mongodb
- android - Flutter ios 无法运行,获取小部件库异常和丢失设备连接
- ajax - 在 Wordpress 前端使用 AJAX 加载 php 文件