在sql脚本中重复出现的时间段

时间:2012-10-02 03:15:25

标签: sql sql-server

情况:

用户创建包含日期字段(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 

2 个答案:

答案 0 :(得分:0)

这是Microsoft SQL吗?这是Express版吗?只要它不是Express,您可能需要考虑使用SQL Agent服务,该服务允许您安排可以针对数据库运行的任务。一旦达到30天,您希望它与记录有什么关系?

答案 1 :(得分: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