使用SQL Server,我有一个发布日期(dateTime
)的列。我想报告上个月(从查看日期)到本月和下个月的所有内容。
所以基本上整整3个月。
写这个的最好方法是什么?
答案 0 :(得分:2)
也许像SELECT /*what_you_want*/ from launches WHERE lauchDate BETWEEN DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) - 1, '19000101') AND DATEADD(MONTH, DATEDIFF(MONTH, '19000101', GETDATE()) + 2, '19000101')
答案 1 :(得分:2)
你在找这样的东西吗?
DECLARE
@StartDate DATETIME,
@EndDate DATETIME
SELECT
@StartDate = DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - 1, 0),
@EndDate = DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 2, 0)
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()), 0), -- beginning of this month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) - 1, 0), -- beginning of last month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 1, 0) -- beginning of next month
-- DATEADD(MM, DATEDIFF(MM, 0, GETDATE()) + 2, 0) -- beginning of two months from now
SELECT
*
FROM
[Table]
WHERE
[LaunchDate] >= @StartDate
AND [LaunchDate] < @EndDate
这将为您提供从上个月开始到现在两个月开始之前的所有结果(整整3个月的范围)
答案 2 :(得分:-1)
SELECT Foo
FROM Bar
WHERE LaunchDate >= DATEADD(mm, -1, GETDATE())
AND LaunchDate <= DATEADD(mm, 1, GETDATE())