我需要检索3个月的数据,例如
我在datetime列中有数据。
Date_Column
11/22/2012
12/22/2012
01/22/2013
当我通过日期12/22/2012时,我需要上面的输出。
我正在使用此但未获得结果。
where
MONTH(Date_Column) BETWEEN MONTH(DATEADD(M,DATEDIFF(M,0,'12/22/2012')-1,0))
AND MONTH(DATEADD(M,DATEDIFF(M,0,'12/22/2012')+1,0))
AND YEAR(Date_Column)=YEAR('12/22/2012')
Group By Month(Date_Column), YEAR(Date_Column)..
提前致谢
答案 0 :(得分:1)
如果您想要前一个月,当月和下个月的所有数据
DECLARE @date datetime = '2012-12-22'
SELECT
*
FROM
yourtable
WHERE
Date_Column >= DATEADD(M,DATEDIFF(M,0,@date)-1,0) AND
Date_Column < DATEADD(M,DATEDIFF(M,0,@date)+2,0)
作为文档
DECLARE @date datetime = '2012-12-22'
SELECT
DATEADD(M,DATEDIFF(M,0,@date)-1,0) [From],
DATEADD(M,DATEDIFF(M,0,@date)+2,0) [To]
返回:
From To
2012-11-01 2013-02-01
答案 1 :(得分:0)
我认为你需要写如下:
where
MONTH(Date_Column) BETWEEN MONTH(DATEADD(M,-1,'12/22/2012'))
AND MONTH(DATEADD(M,+1,'12/22/2012'))
或
where
Date_Column BETWEEN DATEADD(M,-1,'12/22/2012')
AND DATEADD(M,+1,'12/22/2012')
答案 2 :(得分:0)
试试这个,
Declare @CurDate datetime
Declare @StartDate datetime
Declare @EndDate datetime
Select @CurDate = GETDATE() --Pass Your Date As parameter
Select @EndDate=DateAdd(M,+1,@CurDate)
Select @StartDate= DateAdd(M,-1,@CurDate)
Select @CurDate
Select @EndDate
Select @StartDate
WHERE (MONTH(@StartDate) BETWEEN MONTH(@EndDate) AND MONTH(@StartDate))
AND (YEAR(@StartDate) BETWEEN YEAR(@EndDate) AND YEAR(@StartDate))
答案 3 :(得分:0)
试试这个:
这实际上是基于ACCESS,但是如果你能够在sql中转换它,我相信这会起作用
WHERE (((DateDiff("m",Date_Column,'12/22/2012'))=1)) or
(((DateDiff("m",Date_Column,'12/22/2012'))=0)) or (((DateDiff("m",Date_Column,'12/22/2012'))=-1))
我认为这是必须用SQL编写的:
WHERE Date_Column = DATEDIFF(M, 1 , '12/22/2012') OR
Date_Column = DATEDIFF(M, 0 , '12/22/2012') OR
Date_Column = DATEDIFF(M, -1 , '12/22/2012')