我已经编写了SQL来选择过去三个月的用户数据,但我认为目前它每天更新。
我想改变它,以便现在十月它不计算Octobers数据,而是七月到九月数据,并在我们搬到十一月时改为八月到十月
这是我目前获得的SQL:
declare @Today datetime
declare @Category varchar(40)
set @Today = dbo.udf_DateOnly(GETDATE())
set @Category = 'Doctors active last three months updated'
declare @last3monthsnew datetime
set @last3monthsnew=dateadd(m,-3,dbo.udf_DateOnly(GETDATE()))
delete from LiveStatus_tbl where Category = @Category
select @Category, count(distinct U.userid)
from UserValidUKDoctor_vw U
WHERE LastLoggedIn >= @last3monthsnew
我如何编辑它来做到这一点?
答案 0 :(得分:2)
WHERE LastLoggedIn >= DATEADD(month, DATEDIFF(month, 0, GETDATE())-3, 0)
AND LastLoggedIn < DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)
上述声明将在7月至本月初之前返回任何结果。
答案 1 :(得分:0)
参考此答案以获取该月的第一天:
<强> How can I select the first day of a month in SQL? 强>
您可以检测月份限制,如下所示:
select DATEADD(month, DATEDIFF(month, 0, getdate()) - 3, 0) AS StartOfMonth
select DATEADD(month, DATEDIFF(month, 0, getdate()), 0) AS EndMonth
然后您可以将其添加到变量中或直接添加到WHERE
子句中:
declare @StartDate datetime
declare @EndDate datetime
set @StartDate = DATEADD(month, DATEDIFF(month, 0, getdate()) - 3, 0)
set @EndDate = DATEADD(month, DATEDIFF(month, 0, getdate()), 0)
select @Category, count(distinct U.userid)
from UserValidUKDoctor_vw U
where LastLoggedIn >= @StartDate AND LastLoggedIn < @EndDate
或者:
select @Category, count(distinct U.userid)
from UserValidUKDoctor_vw U
where LastLoggedIn >= DATEADD(month, DATEDIFF(month, 0, getdate()) - 3, 0)
and LastLoggedIn < DATEADD(month, DATEDIFF(month, 0, getdate()), 0)
答案 2 :(得分:0)
如何使用BETWEEN?
WHERE LastLoggedIn
BETWEEN
DATEADD(month, DATEDIFF(month, 0, GETDATE())-3, 0)
AND
DATEADD(month, DATEDIFF(month, 0, GETDATE()), 0)