9

我想检索两个日期之间不同年份的列表。

例如,从25/12/200614/11/2013,结果应如下所示:

2006
2007
2008
2009
2010
2011
2012
2013

这在 SQL Server 中可行吗?

4

5 回答 5

22

像这样的日期1/2/2013是不明确的:根据区域设置,它可以是 2 月 1 日,也可以是 1 月 2 日。因此,YYYY-MM-DD在与数据库对话时使用日期格式是个好主意。

您可以使用递归 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

SQL Fiddle 的示例。

于 2013-05-31T12:43:52.390 回答
2

在 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
于 2013-05-31T12:51:00.210 回答
1
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

打开查询并尝试:

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)
于 2013-05-31T12:57:21.527 回答
0

首先,创建一个日历表。然后你只需查询年份:

select distinct YearNumber
from dbo.Calendar
where [Date] between '20061225' and '20131114'
order by YearNumber
于 2013-05-31T13:01:40.957 回答
0

我的两分钱:

由于 OP 的示例实际上是一小组值,我想我会给出一个不依赖于递归/循环或创建其他对象(例如函数/日期表)的答案。它只是使用 Top 子句。

在 SQL Server 2016 上测试

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. The (@startYear - 1) is to retain the start year
SELECT TOP (@endYear - (@startYear - 1)) COUNT([object_id]) OVER (ORDER BY [object_id]) + (@startYear - 1) -- Add initial start year to Count 
FROM sys.all_objects;

希望这是一个不同的看法。

于 2020-11-09T13:26:13.183 回答