Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to return list of years since a specific year

I need a list of years as a recordset starting with 2004 to current year (in desc order), without writing a stored procedure. Is this possible? (SQL Server 2005). So it should return:

2009
2008
2007
2006
2005
2004

like image 789
Graeme Avatar asked Mar 09 '09 15:03

Graeme


People also ask

How do I get all years between two dates in SQL?

It simply uses the Top clause. DECLARE @startYear smallint; SET @startYear = YEAR ('2006-12-25'); DECLARE @endYear smallint; SET @endYear = YEAR('2013-11-14'); -- Top uses expression to bring in N number of rows.

How do I select a specific year from a date in SQL?

The EXTRACT() function returns a number which represents the year of the date. The EXTRACT() function is a SQL standard function supported by MySQL, Oracle, PostgreSQL, and Firebird. If you use SQL Server, you can use the YEAR() or DATEPART() function to extract the year from a date.

How do you check for consecutive years in SQL?

SQL Fiddle. The trick is to - per contact - subtract the running count ( row_number() ) from each year. Consecutive rows produce the same group number ( grp ). the number itself has no meaning, it just identifies groups per contact . Then count, sort, get the maximum count.


2 Answers

This gets all years from 2004 to the present, using a recursive CTE:

with yearlist as  (     select 2004 as year     union all     select yl.year + 1 as year     from yearlist yl     where yl.year + 1 <= YEAR(GetDate()) )  select year from yearlist order by year desc; 
like image 76
Joshua Carmody Avatar answered Sep 19 '22 07:09

Joshua Carmody


Updated to return current year plus previous 5 years. Should be very fast as this is a small recordset.

SELECT YEAR(GETDATE()) as YearNum UNION SELECT YEAR(GETDATE()) - 1 as YearNum UNION SELECT YEAR(GETDATE()) - 2 as YearNum UNION SELECT YEAR(GETDATE()) - 3 as YearNum UNION SELECT YEAR(GETDATE()) - 4 as YearNum UNION SELECT YEAR(GETDATE()) - 5 as YearNum ORDER BY YearNum DESC 
like image 36
DJ. Avatar answered Sep 19 '22 07:09

DJ.