将1个月添加到日期值

时间:2016-04-27 09:42:33

标签: sql sql-server

如何将1个月添加到日期值(第1行)并将其用作下一行的输入以添加月份,直到达到最大月份ID。

declare @tmp table (date date,month_id int);
insert into @tmp values('2014-11-30',1),('2014-11-30',2),('2014-11-30',3),('2014-11-30',4),('2014-11-30',5),('2014-11-30',6),('2015-01-01',1),('2015-01-01',2),('2015-01-01',3),('2015-01-01',4);

Result Set

预期产出:

DATE        month_id    derived_date1 
2014-11-30      1       2014-12-30 
2014-11-30      2       2015-01-30 
2014-11-30      3       2015-02-28 
2014-11-30      4       2015-03-28 
2014-11-30      5       2015-04-28 
2014-11-30      6       2015-05-28 
2015-01-01      1       2015-02-01 
2015-01-01      2       2015-03-01 
2015-01-01      3       2015-04-01 
2015-01-01      4       2015-05-01

4 个答案:

答案 0 :(得分:1)

递归CTE

declare @tmp table (date date,month_id int);
insert into @tmp values('2014-11-30',1),('2014-11-30',2),('2014-11-30',3),('2014-11-30',4),('2014-11-30',5),('2014-11-30',6),('2015-01-01',1),('2015-01-01',2),('2015-01-01',3),('2015-01-01',4);

;with cte as
(
    select date, month_id, DATEADD(MONTH, 1, date) as derived_date1 from @tmp where month_id = 1
    union all select t.date, t.month_id, DATEADD(MONTH, 1, cte.derived_date1) from cte inner join @tmp t on cte.date = t.date and cte.month_id = t.month_id - 1
)
select * from cte order by date, month_id

答案 1 :(得分:0)

你可以试试这个

DATEADD()函数添加或减去日期的指定时间间隔。

    Declare @tmp table (date date,month_id int);
    Insert into @tmp values('2014-11-30',1),('2014-11-30',2),('2014-11-30',3),('2014-11-30',4),('2014-11-30',5),('2014-11-30',6),('2015-01-01',1),('2015-01-01',2),('2015-01-01',3),('2015-01-01',4);
    SELECT date as Original_Date,month_id as Month_Id,DATEADD(MONTH,month_id,date) as Derived_date from @tmp

Result Set

答案 2 :(得分:0)

您可以使用数字或计数表

来完成此操作
declare @numbers table(no int)
insert into @numbers 
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9 union all
select 10 union all
select 11 union all
select 12 

declare @month_value int, @date datetime
select @month_value=12, @date='2014-01-30'

declare @tmp table (date date,month_id int);
insert into @tmp 
select dateadd(month,no-1,@date),no from @numbers where no<=@month_value

select * from @tmp

答案 3 :(得分:0)

对于给定的日期和月份范围,您可以在数据上使用CTE和连接:

declare @StartMonth int = 1
declare @EndMonth int = 6

declare @DateToPopulate Date = '2014-11-30'
declare @tmp table (original date,month_id int, derived date)
;

with month_range as
(
    select @StartMonth as Month
    union all
    select Month+1 from month_range where Month+1 <=@EndMonth
),
generated_data as
(
    select @DateToPopulate as OriginalDate, Month as MonthID, DATEADD(month,Month,@DateToPopulate) as DerivedDate
    from month_range
)
insert into @tmp
select * from generated_data