我想检索两个日期之间不同年份的列表。
例如,从25/12/2006
到14/11/2013
,结果应如下所示:
2006
2007
2008
2009
2010
2011
2012
2013
这在SQL Server中是否可行?
答案 0 :(得分:17)
像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
答案 1 :(得分: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
答案 2 :(得分: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)
答案 3 :(得分:0)
首先,创建一个calendar table。然后你只需查询年份:
select distinct YearNumber
from dbo.Calendar
where [Date] between '20061225' and '20131114'
order by YearNumber
答案 4 :(得分: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;
希望这是另一回事。