如何从当前日期获得仅6个月的数据?

时间:2012-07-30 12:13:58

标签: sql-server-2008 tsql

我有一个只包含Month和Year字段的表作为int。 鉴于输入说月份,6个月。 我需要预测6个月大的数据。

例如,我有2001年的数据,第一个Janaury直到日期。鉴于输入为6个月,所以我必须回到6个月 从cuurent date获得结果。

输出将是2001年1月至2012年1月的数据。

我使用正确的子字符串字符串比较完成了程序。(讨厌的黑客攻击)

有没有明显的方法呢?

DDL

Declare @t table (Mnth int, Yr int)
Insert Into @t 

-- 2011
Select 1,2011 Union All select 2,2011 Union All Select 3, 2011 Union ALL Select 4,2011 Union ALL
Select 5,2011 Union All select 6,2011 Union All Select 7, 2011 Union ALL Select 8,2011 Union ALL
Select 9,2011 Union All select 10,2011 Union All Select 11, 2011 Union ALL Select 12,2011 Union ALL

--2012
Select 1,2012 Union All select 2,2012 Union All Select 3, 2012 Union ALL Select 4,2012 Union ALL
Select 5,2012 Union All select 6,2012 Union All Select 7, 2012 Union ALL Select 8,2012 Union ALL
Select 9,2012 Union All select 10,2012 Union All Select 11, 2012 Union ALL Select 12,2012

Declare @inputMonth int = 6

我正在尝试没有字符串转换

Select Mnth,Yr,YEAR(DATEADD(mm,-@inputMonth,getdate())),MONTH(DATEADD(mm,-@inputMonth,getdate()))
From @t
WHERE   YEAR(DATEADD(mm,-@inputMonth,getdate())) < Yr
AND MONTH(DATEADD(mm,-@inputMonth,getdate())) < Mnth

但它不起作用

由于

4 个答案:

答案 0 :(得分:4)

您可以随时转换为日期时间并进行比较。

类似的东西:

WHERE
    CONVERT(Datetime, 
        CONVERT(nvarchar(4), YearPart) + '-' + CONVERT(nvarchar(2), MonthPart) + '-01')
    ) > DATEADD(month, -6, GETUTCDATE())

即。例如,连接两列以产生CONVERT(Datetime, "2011-1-01")

正如this answer to another question指出的那样,如果您不想进行字符串转换,则必须添加一系列DATEADD0,即{{1} }}

1900-01-01

答案 1 :(得分:0)

没有施法。

Select *
From your table
Where  (yr= @someYear and mt between @someMonth-6 and @someMonth) or
       (@someMonth <6 and yr =@someYear - 1 and mt >= 12-(6-@someMonth) )

答案 2 :(得分:0)

意识到我没有考虑过,新的解决方案:

declare @m int 
set @m = 11

declare @startDate datetime
set @startDate =  dateadd(mm,-@m,getdate())
select yr,mnth
from t
where
DateAdd(day, 1, 
      DateAdd(month, mnth - 1, 
          DateAdd(Year,yr-1900, 0))) >@startDate 
and
DateAdd(day, 1, 
      DateAdd(month, mnth - 1, 
          DateAdd(Year,yr-1900, 0)))  < getDate()

答案 3 :(得分:0)

试试这个..

DECLARE @CurrentMonth tinyint,@CurrentYear tinyint
SELECT @currentMonth=Datepart(mm,getdate())
SELECT @CurrentYear=Datepart(yy,getdate())

IF((@currentmonth-6)<0)
 begin
  SELECT month,year FROM @t WHERE year =(@CurrentYear-1) AND month >(@currentMonth+6) 
   UNION ALL
  SELECT month,year FROM @t WHERE year=@CurrentYear AND month <= @CurrentMonth 
 end
ELSE
 begin
  SELECT month,year from @t WHERE year=@CurrentYear AND month between @CurrentMonth-6
  AND @CurrentMonth+1
 end
相关问题