[英]Merge two records date if ToDate equal second FromDate SQL Server?
[英]SQL Server How can we write a sql function which returns the records where getdate() is between FromDate and Todate
我们如何编写一个 sql function 来返回 getdate() 在 FromDate 和 Todate 之间的记录,如下所示
if getdate() exists between FromDate and Todate then return
elseif DateAdd(Year, -1, getdate()) is between FromDate and Todate.
elseif DateAdd(Year, -2, getdate()) is between FromDate and Todate.
我的表
ProductID FromDate Todate
A 1/2/2022 1/2/2023
A 1/2/2021 1/2/2022
A 1/2/2020 1/2/2021
A 1/2/2019 1/2/2020
B 1/2/2020 1/2/2021
B 1/2/2019 1/2/2020
C 1/2/2019 1/2/2020
C 1/2/2018 1/2/2019
假设 getdate() 是 1/10/2022 结果应该如下
ProductID FromDate Todate Active
A 1/2/2021 1/2/2022
B 1/2/2020 1/2/2021
C 1/2/2019 1/2/2020
我相信你的意思是“我怎样才能从这个表中返回今天的日期、一年前或两年前的日期在开始日期和结束日期之间的记录?”
在这种情况下,你很接近,但这应该有效:
WITH dates
AS
(
SELECT DATEADD(Year,i,CAST(GETDATE() AS Date)) AS datecheck
FROM (VALUES (0),(-1),(-2)) t(i)
)
SELECT ProductID, FromDate, ToDate
FROM Mytable, dates
WHERE datecheck BETWEEN FromDate AND ToDate;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.