在SQL Server中用逗号CTE分隔的年份

时间:2017-06-26 15:46:55

标签: sql sql-server common-table-expression

我有一个名为StartYear的字段,我的字段的值是2000.我有另一个名为EndYear的字段,我的字段的值是2005。

我想创建一个名为YearsInTheProgram的字段,其值为2005,2004,2003,2002,2001,2000。

我的每一行都有不同的值,所以本质上我希望这个字段能区分我的字段。

我能够找到一些可行的东西,但这会给我一个不同行的值。但是,我希望所有这些都在一行中。

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

2 个答案:

答案 0 :(得分:0)

declare @tmp varchar(250)
SET @tmp = ''

;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 @tmp = @tmp + convert(varchar(500), yr) + ', ' from CTE
select SUBSTRING(@tmp, 0, LEN(@tmp)) as yr

答案 1 :(得分:0)

您可以使用此CTE来增加您的一串年。

DECLARE @STARTYEAR varchar(10) = '2006-12-25'
DECLARE @ENDYEAR varchar(10) = '2013-11-14'

;with  CTE as
        (
        select  datepart(year, @STARTYEAR) as yr, CAST(datepart(year, @STARTYEAR) AS VARCHAR(MAX)) as c
        union all
        select  yr + 1 as yr, CAST(concat(c, ',', yr+1) AS VARCHAR(MAX)) as c
        from    CTE
        where   yr < datepart(year, @ENDYEAR)
        )
select  yr, c
from    CTE
where (yr = datepart(year, @ENDYEAR))

这里是从DB表中获取的StartYear和EndYear。

create table #yr (id int, start varchar(20), stop varchar(20))
insert into #yr values(1,'2005-01-01','2010-12-10'), (2,'2008-01-01','2011-12-10'), (3,'2007-01-01','2013-12-10'), (4,'2009-01-01','2012-10-10')

;with  CTE as
        (
        select  start as start, datepart(year, start) as yr, CAST(datepart(year, start) AS VARCHAR(MAX)) as c from #yr
        union all
        select  CTE.start as start, yr + 1 as yr, CAST(concat(c, ',', yr+1) AS VARCHAR(MAX)) as c
        from    CTE join #yr on #yr.start = CTE.start
        where   yr < datepart(year, stop)
        )
select  id, #yr.start, #yr.stop, c
from    CTE join #yr on #yr.start = CTE.start
where (yr = datepart(year, stop))

以下结果

4   2009-01-01  2012-10-10  2009,2010,2011,2012
3   2007-01-01  2013-12-10  2007,2008,2009,2010,2011,2012,2013
2   2008-01-01  2011-12-10  2008,2009,2010,2011
1   2005-01-01  2010-12-10  2005,2006,2007,2008,2009,2010