下面是我的 SQL 语句
DECLARE @dStart datetime ,
@dEnd datetime
SET @dEnd = GETDATE()
SET @dStart = DATEADD(mm, -6, @dEnd)
Select * from MyTable
Where TheDate Between @dStart AND @dEnd
这将返回今天减去 6 个月数据的所有记录。
但我想要这个月的数据加上前 5 个月的数据。
目前它也将从 3 月开始返回记录。
下面是我的 SQL 语句
DECLARE @dStart datetime ,
@dEnd datetime
SET @dEnd = GETDATE()
SET @dStart = DATEADD(mm, -6, @dEnd)
Select * from MyTable
Where TheDate Between @dStart AND @dEnd
这将返回今天减去 6 个月数据的所有记录。
但我想要这个月的数据加上前 5 个月的数据。
目前它也将从 3 月开始返回记录。
代替
DATEADD(mm, -6, @dEnd)
你可能会使用
dateadd(month, datediff(month, 0, @dEnd) - 5, 0)
这会将日期截断为当月的第一天并从中减去五个月。
declare @date datetime
declare @months int
declare @year int
set @months=month(GETDATE())
set @year=month(GETDATE())
set @date=getdate()
(Select * from MyTable Where TheDate Between (01/@months-5/@year) AND (01/@months/@year) ) union (Select * from MyTable Where TheDate Between (01/@months/@year) AND @date)
DECLARE @dStart datetime ,
@dEnd datetime
SET @dEnd = GETDATE()
SET @dStart = DATEADD(mm, -4, @dEnd)