简体   繁体   English

SQL Where条件的年数

[英]SQL Where condition for number of years

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

SELECT
 *
FROM
MyTable a
WHERE
a.FiscalYear in (

When @NumberofPriorYears is 2 then i want to pass @currentYear-@NumberofPriorYears (ie 2014,2013,2012) or when @NumberofPriorYears is null then pass @currentYear ie 2014. 当@NumberofPriorYears为2时,我想传递@currentYear-@NumberofPriorYears (即2014、2013、2012),或者当@NumberofPriorYears为null时,传递@currentYear即2014。

Appreciate any help on this. 感谢对此的任何帮助。

Try this 尝试这个

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
SELECT *
FROM MyTable a
WHERE @currentYear - a.FiscalYear <= ISNULL(@numberOfPriorYears, 0)

If you want to be able to pass in a previous year instead of just the current year (eg see 2011-2012 instead of 2011-2014) you can use BETWEEN 如果您希望能够通过上一年而不是仅当年(例如,看到2011-2012而不是2011-2014),则可以使用BETWEEN

WHERE a.FiscalYear BETWEEN @currentYear - ISNULL(@numberOfPriorYears, 0) AND @currentYear
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
  )

Can you use a range? 你可以使用范围吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM