如何在SQL Server中基于重定价年数计算最后与下次重定价日期
SQL Server 计算最后/下次重定价日的正确实现
针对你的需求,结合示例数据的逻辑,以下是SQL Server中基于Value_Date、Reprice_in_years和reporting_date计算Last_reprice_date(最后重定价日)与Next_Reprice_date(下次重定价日)的正确SQL语句:
SELECT A.*, -- 计算最后重定价日:取小于等于reporting_date的最近一次重定价日,未发生则为NULL CASE WHEN FLOOR(DATEDIFF(month, A.Value_Date, A.reporting_date) / (A.Reprice_in_years * 12)) >= 1 THEN DATEADD(month, FLOOR(DATEDIFF(month, A.Value_Date, A.reporting_date) / (A.Reprice_in_years * 12)) * (A.Reprice_in_years * 12), A.Value_Date) ELSE NULL END AS Last_reprice_date, -- 计算下次重定价日:取大于reporting_date的下一次重定价日 CASE WHEN FLOOR(DATEDIFF(month, A.Value_Date, A.reporting_date) / (A.Reprice_in_years * 12)) >= 1 THEN DATEADD(month, (FLOOR(DATEDIFF(month, A.Value_Date, A.reporting_date) / (A.Reprice_in_years * 12)) + 1) * (A.Reprice_in_years * 12), A.Value_Date) ELSE DATEADD(month, A.Reprice_in_years * 12, A.Value_Date) END AS Next_Reprice_date FROM TABLE_REFERENCE A
逻辑说明
- 周期转换:将
Reprice_in_years转换为月数(Reprice_in_years * 12),解决小数年份无法直接用于日期函数的问题,同时保证半年(0.5年)、两年等周期的计算准确性。 - 已完成重定价次数计算:通过
DATEDIFF(month, Value_Date, reporting_date)计算初始日与报告日的月份差,除以周期月数后取整,得到已完成的重定价次数k。 - 最后重定价日:若
k≥1(已发生过重定价),则取初始日加上k个周期的日期;若k<1(首次重定价未到),则返回NULL。 - 下次重定价日:若已发生过重定价,取最后重定价日再加一个周期的日期;若未发生,取初始日加第一个周期的日期。
内容的提问来源于stack exchange,提问作者Dilaniv
相关产品推荐
相关产品推荐

