这符合规定的要求(前两个月的最后一周):
SET DATEFIRST 1;
DECLARE @s DATE = GETDATE(), @s1 DATE, @s2 DATE;
SET @s = GETDATE();
-- last day of last month:
SET @s1 = DATEADD(DAY, -DAY(@s), @s);
-- last day of previous month:
SET @s = DATEADD(MONTH, -1, @s);
SET @s2 = DATEADD(DAY, -DAY(@s), @s);
SELECT
@s1 = DATEADD(DAY, -7, DATEADD(DAY, -DATEPART(WEEKDAY, @s1) % 7, @s1)),
@s2 = DATEADD(DAY, -7, DATEADD(DAY, -DATEPART(WEEKDAY, @s2) % 7, @s2));
SELECT col1, col2, etc.
FROM dbo.table
WHERE
(date_column >= @s1 AND date_column < DATEADD(DAY, 7, @s1)
OR
(date_column >= @s2 AND date_column < DATEADD(DAY, 7, @s2);
为了使这更具动态性(您应该首先尽力说明这些要求,而不是在人们投入大量工作之后),您可以说:
DECLARE @NumberOfMonthsIReallyWanted INT = 3;
DECLARE @i INT = 1, @d DATE = GETDATE();
DECLARE @t TABLE(d DATE);
WHILE @i <= @NumberOfMonthsIReallyWanted
BEGIN
SET @d = DATEADD(MONTH, -@i, @d)
INSERT @t(s) SELECT DATEADD(DAY, -7, DATEADD(DAY,
-DATEPART(WEEKDAY, DATEADD(DAY, -DAY(@d), @d)) % 7,
DATEADD(DAY, -DAY(@d), @d)));
SET @i += 1;
END
SELECT src.col1, src.col2, etc.
FROM dbo.table AS src
INNER JOIN @t AS t
ON src.date_column >= t.d AND src.date_column < DATEADD(DAY, 7, t.d);
请不要让任何人说服您使用LIKE
日期比较查询。这不仅会杀死 sargability(意味着不能使用索引),而且对于这样的问题,您如何确定要匹配的字符串模式?困难不在于构建WHERE
子句,而在于为魔术(Your Dates go here)
占位符填写什么。当你找到日期范围时,你真的想要 14 个单独的LIKE
表达式吗?我不会。