DATEDIFF 関数を使用して、日付の差を日数で計算できます。モジュラス (%) 演算子を使用して、除算の「剰余」を取得できます。2つを組み合わせると、次のようになります。
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