根据Where子句SQL Server修改日期函数

时间:2017-06-01 21:09:49

标签: sql-server date case

目前我的个案陈述是基于当月的第一天。

SELECT
[TicketNbr] AS 'Ticket Nbr'
-- 1st day of this month
, ( CASE  WHEN [date_entered] >=  DATEADD(day,-1, GETDATE())  THEN 1  ELSE 0  END) AS '1=Opened Within Last 24HR 0=No'
FROM [v_rpt_Service] WITH(NOLOCK) 
WHERE ([date_entered] >= '2017-04-01T11:24:00.000' AND [date_entered] < '2017-05-01T11:24:00.000')
GROUP BY [TicketNbr]

但是我想修改它以便它会根据日期范围进行调整 在where子句中。 (这可以是任何日期范围。)

如何在没有变量的情况下这样做?

1 个答案:

答案 0 :(得分:2)

听起来你只需要变量

declare @startDate datetime = '2017-04-01 11:24:00'
declare @endDate datetime = '2017-05-01 11:24:00'

SELECT
[TicketNbr] AS 'Ticket Nbr'
-- 1st day of this month
, ( CASE  WHEN [date_entered] between @startDate and @endDate  THEN 1  ELSE 0  END) AS '1=Opened Within Date Range 0= No'
FROM [v_rpt_Service] WITH(NOLOCK) 
WHERE ([date_entered] >= startDate  AND [date_entered] < @endDate)
GROUP BY [TicketNbr]