我的报告生成器应该从上个月的第三个星期四获得所有条目。 我如何在ms sql server中实现这个?
答案 0 :(得分:2)
您可以使用以下内容:
WHERE DATEPART(dw,[YourDateColumn]) = 5 -- Thursday
AND DATEPART(d,[YourDateColumn]) BETWEEN 15 AND 21 -- Third thursday in month
AND DATEDIFF(m,GETDATE(),[YourDateColumn])=-1 -- Last month
但是你需要知道,由于这些功能,查询可能会很慢 另见:Avoid Using Function in WHERE Clause. Why?
答案 1 :(得分:0)
对于这样的事情,使用日历表会更容易。见
答案 2 :(得分:0)
以下代码查找上个月的第三个星期四 (last = previous = last = current?if last = current,用datedd替换dateadd(month,-1,getdate())和getdate())。
您可以将其包装到函数中并在查询的WHERE子句中使用 或者在使用变量过滤之前计算它, 所以你的查询看起来像
SELECT...WHERE dt >= fn()
或
SELECT...WHERE dt >= @dt
option(recompile)
因此可以使用索引(如果有的话)
with nums as -- numbers 1..31
(
select number as n
from master..spt_values
where type = 'p'
and number between 0 and 30
)
, thur as
(
select dt,
dd,
ROW_NUMBER() over (order by dt) as rn
from nums cross apply
(
select cast(convert(char(6), dateadd (month, -1, getdate()), 112) + '01' as date) as dt0 -- the first of last month
)a
cross apply( select dateadd(day, n, dt0) as dt) a1
cross apply( select datename(dw, dt) as dd, month(dt) as mm) a2
where dd = 'Thursday' and mm = month(dt0)
)
select dt
from thur
where rn = 3;