datediff(quarter,date,getdate())
返回日期是否在不同的季度,而不是它们是否正好相隔四分之一,我认为这是您正在寻找的。
因此,我希望找到 3 个月前的倍数的日期,并且该日期也位于该月的同一天。
SQL小提琴
MS SQL Server 2008 架构设置:
CREATE TABLE tableA
([UserID] int, [Date] date);
INSERT INTO tablea
([UserID], [Date])
VALUES
(4582, '2012-09-04'),
(4665, '2012-09-05'),
(1251, '2012-06-05'),
(6538, '2011-08-04'),
(7485, '2011-09-05');
查询 1:
SELECT *
FROM TableA
WHERE
-- Only get dates which are a multiple of 3 months previosuly
DATEDIFF(mm, [DATE], GETDATE()) % 3 = 0
-- only get dates that fall on the same day of the month
AND DAY(GETDATE()) = DAY([Date])
结果:
| USERID | DATE |
-----------------------
| 4665 | 2012-09-05 |
| 1251 | 2012-06-05 |
| 7485 | 2011-09-05 |