SQL其中条件的年数

时间:2014-10-02 21:57:58

标签: sql sql-server

Declare int @NumberofPriorYears=2;
Declare int @currentYear=2014;

SELECT
 *
FROM
MyTable a
WHERE
a.FiscalYear in (

当@NumberofPriorYears为2时,我想通过@currentYear-@NumberofPriorYears(即2014,2013,2012) 或当@NumberofPriorYears为空时,则传递@currentYear,即2014年。

感谢您的任何帮助。

4 个答案:

答案 0 :(得分:0)

试试这个

Declare int @numberofyears=2;
Declare int @currentYear=2014;

set @currentYear = datepart(year,getdate())


SELECT
 *
FROM
MyTable a
WHERE
datepart(year,a.FiscalYear) between @currentYear and @currentYear+@numberofYears

答案 1 :(得分:0)

SELECT *
FROM MyTable a
WHERE @currentYear - a.FiscalYear <= ISNULL(@numberOfPriorYears, 0)

如果您希望能够过去一年而不是当前一年(例如,见2011-2012而不是2011-2014),您可以使用BETWEEN

WHERE a.FiscalYear BETWEEN @currentYear - ISNULL(@numberOfPriorYears, 0) AND @currentYear

答案 2 :(得分:0)

Declare int @numberofyears=2;
Declare int @currentYear=2014;

SELECT *
FROM  MyTable a
WHERE
    ( YEAR(a.FiscalYear) >= YEAR(GETDATE()) -  @numberofyears
      AND 
      @numberofyears IS NOT NULL
    )
OR
 ( YEAR(a.FiscalYear) = YEAR(GETDATE())
    AND 
    @numberofyears IS NULL
  )

答案 3 :(得分:0)

你能使用范围吗?

a.FiscalYear >= @currentYear-isnull(@NumberofPriorYears,0)
and a.FiscalYear < @currentYear+1