[英]List all dates between range
I've seen this asked before, but couldn't get an answer that worked. 我以前曾问过这个问题,但找不到有效的答案。
I have 2 columns - startyear
and endyear
. 我有2列-
startyear
和endyear
。 I want to create a list of all years between the start and end year. 我想创建一个开始和结束年度之间所有年份的列表。 So if the row has a
startyear
of 2010 and an endyear
of 2016, I want the list to show 2010, 2011, 2012, etc. 因此,如果该行的开始
startyear
为2010年, endyear
为2016年,我希望该列表显示2010年,2011年,2012年等。
Do I have to somehow grab the oldest startyear
and newest endyear
throughout all rows? 我是否必须以某种方式获取所有行中最早的
startyear
和最新的endyear
?
SELECT StartYear, EndYear
FROM TestYear
You can do this with a recursive CTE
: 您可以使用递归
CTE
进行此操作:
;With MaxMin As
(
Select Min(StartYear) As First,
Max(EndYear) As Last
From TestYear
), Years (Year) As
(
Select First From MaxMin Union All
Select Year + 1
From Years
Where Year < (Select Last From MaxMin)
)
Select *
From Years
Try something like this in a Stored Procedure. 在存储过程中尝试类似的操作。
SELECT * INTO #FileDates
FROM (SELECT distinct year(startyear) as year from filename )
SELECT * INTO #FileDates2
FROM (SELECT distinct year(endyear) as year from filename )
select distinct year from #FileDate, #FileDate2
Also you might want to check out: http://www.sqlservercentral.com/stairway/119892/ 另外,您可能想签出: http : //www.sqlservercentral.com/stairway/119892/
Use a recursive cte to do this. 使用递归cte执行此操作。
declare @startyear int = 2010; --or any other number or a select query
declare @endyear int = 2020; --or any other number or a select query
with years(yr) as
(
select @startyear
union all
select yr+1 from years where yr < @endyear
)
select * from years;
Sample Data 样本数据
Declare @t Table (StartYear INT , EndYear INT)
INSERT INTO @t Values (2010 , 2011), (2012 , 2016);
Query 询问
WITH X AS (
Select MIN(StartYear) MinYear
,MAX(EndYear) MaxYear
FROM @t
)
Select TOP ((Select MaxYear FROM X)
- (Select MinYear FROM X) + 1)
ROW_Number() Over (Order by (Select NULL))
+ (Select MinYear FROM X) -1 rn
FROM master..spt_values a
Cross Join master..spt_values b
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.