1

情况:

用户创建一个包含日期字段 (DateOpened) 的案例记录,并希望每 30 天向客户发送一次跟进,直到案例结束。用户将定期(可能每周)运行查询,并提供“从”和“到”日期范围以指定记录可能在 30 天的多个时间段内。

请求:

我需要一种方法来识别用户指定的日期范围包括自 DateOpened 日期起 30 天的倍数的记录。

更新 这是昨晚看三流电视节目时突然想到的!

SELECT 
.... 
FROM 
....
WHERE
(CAST((DATEDIFF(dd, Invoice.DateOpened @EndDate)/30) AS INT) - CAST((DATEDIFF(dd, Invoice.DateOpened, @StartDate)/30) AS INT)) >=1 
OR DATEDIFF(dd, Invoice.DateOpened, @StartDate) % 30 = 0 --this line to capture valid records but where From and To dates are the same 
4

2 回答 2

0

您可以使用 DATEDIFF 函数以天数计算日期之间的差异。您可以使用模数 (%) 运算符来获取除法运算的“余数”。将两者结合起来可以为您提供:

SELECT
    ....
FROM
    ....
WHERE
    --In MS T-SQL, BETWEEN is inclusive.
    DateOpened BETWEEN @UserSuppliedFromDate AND @UserSuppliedToDate
    AND DATEDIFF(dd, DateOpened, getdate()) % 30 = 0

这应该会给你想要的结果。

编辑(在 MSSQL 中尝试这个例子):

DECLARE @Table TABLE
(
    ID integer,
    DateOpened datetime
)

DECLARE @FromDate as datetime = '1/1/2012'
DECLARE @ToDate as datetime = '12/31/2012'

INSERT INTO @Table VALUES (0, '1/1/1982')
INSERT INTO @Table values (1, '1/1/2012')
INSERT INTO @Table VALUES (2, '2/17/2012')
INSERT INTO @Table VALUES (3, '3/16/2012')
INSERT INTO @Table VALUES (4, '4/16/2012')
INSERT INTO @Table VALUES (5, '5/28/2012')
INSERT INTO @Table VALUES (6, '1/31/2012')
INSERT INTO @Table VALUES (7, '12/12/2013')

DECLARE @DateLoop as datetime
DECLARE @ResultIDs as table ( ID integer, DateLoopAtTheTime datetime, DaysDifference integer )

--Initialize to lowest possible value
SELECT @DateLoop = @FromDate

--Loop until we hit the maximum date to check
WHILE @DateLoop <= @ToDate
BEGIN
    INSERT INTO @ResultIDs (ID,DateLoopAtTheTime, DaysDifference)
        SELECT ID, @DateLoop, DATEDIFF(dd,@DateLoop, DateOpened)
        FROM @Table 
        WHERE 
            DATEDIFF(dd,@DateLoop, DateOpened) % 30 = 0
            AND DATEDIFF(dd,@DateLoop,DateOpened) > 0 -- Avoids false positives when @DateLoop and DateOpened are the same
            AND DateOpened <= @ToDate
    SELECT @DateLoop = DATEADD(dd, 1, @DateLoop) -- Increment the iterator
END

SELECT distinct * From @ResultIDs
于 2012-10-02T03:32:38.930 回答
0

这是微软的 SQL 吗?这是快递版吗?只要不是 Express,您可能需要考虑使用 SQL 代理服务,它可以让您安排可以针对数据库运行的任务。一旦达到 30 天,您希望它与记录做什么?

于 2012-10-02T03:17:46.607 回答