Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of distinct years between two dates

Tags:

sql

sql-server

I'd like to retrieve the list of distinct years between two dates.

For example, from 25/12/2006 to 14/11/2013, the result should look like:

2006
2007
2008
2009
2010
2011
2012
2013

Is this possible in SQL Server ?

like image 815
Black Cloud Avatar asked May 31 '13 12:05

Black Cloud


People also ask

How can I get years between two dates in SQL?

To find the difference between dates, use the DATEDIFF(datepart, startdate, enddate) function. The datepart argument defines the part of the date/datetime in which you'd like to express the difference. Its value can be year , quarter , month , day , minute , etc.

How do I show unique birth year in SQL?

tableName::whereNotNull('columnName')->distinct()->get([DB::raw('YEAR(columnName) as year')]); This is select distinct year from a date column in laravel.

Does dateDiff account for leap year?

The dateDiff function divides the days with 29 for February for a leap year and 28 if it is not a leap year. For example, you want to calculate the number of months from September 13 to February 19. In a leap year period, dateDiff calculates the month of February as 19/29 months or 0.655 months.


3 Answers

A date like 1/2/2013 is ambiguous: depending on the regional setting, it can be either Feb 1st, or Jan 2nd. So it's a good idea to use the YYYY-MM-DD date format when talking to the datebase.

You can generate a list of numbers using a recursive CTE:

; with  CTE as
        (
        select  datepart(year, '2006-12-25') as yr
        union all
        select  yr + 1
        from    CTE
        where   yr < datepart(year, '2013-11-14')
        )
select  yr
from    CTE

Example at SQL Fiddle.

like image 163
Andomar Avatar answered Oct 12 '22 22:10

Andomar


CREATE FUNCTION [dbo].Fn_Interval 
(   
    @p1 datetime2, 
    @p2 datetime2
)
RETURNS @dt TABLE 
(
    YearValue int not null
)
AS
BEGIN

    declare @start as int
    declare @end as int

    set @start = DATEPART(year, @p1);
    set @end = DATEPART(year, @p2);

    while (@start <= @end)
    begin
        INSERT @dt
        SELECT @start;
        set @start = @start + 1;
    end

    RETURN;
END

Open a Query and try:

declare @p1 as datetime2;
declare @p2 as datetime2;

set @p1 = '2013-12-31';
set @p2 = '2020-05-05';

select *
from dbo.Fn_Interval(@p1, @p2)
like image 29
Max Avatar answered Oct 12 '22 23:10

Max


Tested on SQL Server 2008

declare @smaller_date date = convert(date, '25/12/2006', 103)
declare @larger_date date = convert(date, '14/11/2013', 103)
declare @diff int
select @diff = DATEDIFF(YY, @smaller_date,  @larger_date)

;with sequencer(runner) as(
select 0 
union all
select sequencer.runner + 1 from sequencer
where runner < @diff
)
select YEAR(@smaller_date) + runner from sequencer
like image 45
iruvar Avatar answered Oct 13 '22 00:10

iruvar