如何根据下一条记录的 [EffectiveDate]-1 in T-SQL (SSMS 2017) 计算到期日期?
How to calculate expiration date based on next record's [EffectiveDate]-1 in T-SQL (SSMS 2017)?
我有以下简单查询,结果 table:
SELECT
[Client_ID],
[ClientName],
[EffectiveDate],
[MedConditionID],
[MedCondition]
FROM
[Medications]
结果Table:
我需要填充 [ExpirationDate] 字段 - 它基于下一条记录的 [EffectiveDate] 字段 - 1.
例如 - 如果生效日期为“1/16/2019”、“10/16/2019”,则“1/16/2019”的 [ExpirationDate] =“10/15/2019”等.
对于最大的生效日期(在这个table中是'3/18/2020'),到期日期应该总是='2050/12/31'
请参阅下面更新的 table(我需要如何填充 [ExpirationDate],我突出显示了第一个和第二个示例):
有什么建议请帮忙
我在考虑一些 Lag() / Lead() 函数,它们将相互比较记录,但不确定
谢谢!
declare @Medications table
(
[Client_ID] int,
[ClientName] varchar(50),
[EffectiveDate] date,
[MedConditionID] int,
[MedCondition] varchar(50)
);
insert into @Medications(Client_Id, ClientName, EffectiveDate, MedConditionId, MedCondition)
values
(100, 'jeffrey', '20190116', 123, 'Alcohol'),
(100, 'jeffrey', '20191016', 123, 'Alcohol'),
(100, 'jeffrey', '20191016', 267, 'Head'),
(100, 'jeffrey', '20191220', 123, 'Alcohol'),
(100, 'jeffrey', '20191220', 267, 'Head'),
(100, 'jeffrey', '20200121', 123, 'Alcohol'),
(100, 'jeffrey', '20200121', 267, 'Head');
select EffectiveDate,
dateadd(day, -1,
lead(EffectiveDate, 1, '20510101' ) over(partition by Client_id, MedConditionId order by EffectiveDate)
) as ExpirationDate,
*
from @Medications;
我有以下简单查询,结果 table:
SELECT
[Client_ID],
[ClientName],
[EffectiveDate],
[MedConditionID],
[MedCondition]
FROM
[Medications]
结果Table:
我需要填充 [ExpirationDate] 字段 - 它基于下一条记录的 [EffectiveDate] 字段 - 1.
例如 - 如果生效日期为“1/16/2019”、“10/16/2019”,则“1/16/2019”的 [ExpirationDate] =“10/15/2019”等.
对于最大的生效日期(在这个table中是'3/18/2020'),到期日期应该总是='2050/12/31'
请参阅下面更新的 table(我需要如何填充 [ExpirationDate],我突出显示了第一个和第二个示例):
有什么建议请帮忙
我在考虑一些 Lag() / Lead() 函数,它们将相互比较记录,但不确定
谢谢!
declare @Medications table
(
[Client_ID] int,
[ClientName] varchar(50),
[EffectiveDate] date,
[MedConditionID] int,
[MedCondition] varchar(50)
);
insert into @Medications(Client_Id, ClientName, EffectiveDate, MedConditionId, MedCondition)
values
(100, 'jeffrey', '20190116', 123, 'Alcohol'),
(100, 'jeffrey', '20191016', 123, 'Alcohol'),
(100, 'jeffrey', '20191016', 267, 'Head'),
(100, 'jeffrey', '20191220', 123, 'Alcohol'),
(100, 'jeffrey', '20191220', 267, 'Head'),
(100, 'jeffrey', '20200121', 123, 'Alcohol'),
(100, 'jeffrey', '20200121', 267, 'Head');
select EffectiveDate,
dateadd(day, -1,
lead(EffectiveDate, 1, '20510101' ) over(partition by Client_id, MedConditionId order by EffectiveDate)
) as ExpirationDate,
*
from @Medications;