如何根据其他列的值将月份添加到日期

时间:2014-07-23 12:20:50

标签: sql sql-server

我有一个PlannedDate和PeriodLength列。我想要一个新列PlannedMonth。 PlannedMonth应该具有基于PlannedDate和PeriodLength的结果集。所以,我想得到的PlannedMonth是

PlannedMonth is PlannedDate + 0, PlannedDate + 1, ... PlannedDate + (PeriodLength - 1)

我已经实现了类似的东西

DECLARE @PeriodLength INT = (SELECT PeriodLength FROM IP WHERE Id = [some_id]),
        @index INT = 1
    WHILE (@index <= @PeriodLength)
    BEGIN
        SELECT 
            PlannedDate, 
            DATEADD (mm, @index, PeriodStartDate) AS 'PlannedMonth',
            @index
        FROM
            IP
        WHERE 
            Id = [some_id]
    SET @index = @index + 1 
END

但是这种方法的问题在于我有多个表,而我想要一个包含所有结果的表。

2 个答案:

答案 0 :(得分:1)

我会用递归CTE来做这件事:

with cte as (
      select id, PlannedDate, 0 as ind, PeriodLength
      from ip
      union all
      select id, dateadd(1, month, PlannedDate), ind + 1, PeriodLength
      from cte
      where ind <= PeriodLength
     )
select *
from cte;

如果您只需要一个IP,则可以在外部查询或第一个子查询中添加where子句。

答案 1 :(得分:0)

这是一个临时表变量。如果有任何错误,则会出现错误。

     DECLARE @tab table(p_date date,p_month date,@index int)
        DECLARE @PeriodLength INT = (SELECT PeriodLength FROM IP WHERE Id = [some_id]),
                @index INT = 1

            WHILE (@index <= @Perio

dLength)
        BEGIN
            insert into @tab SELECT 
                PlannedDate, 
                DATEADD (mm, @index, PeriodStartDate) AS 'PlannedMonth',
                @index
            FROM
                IP
            WHERE 
                Id = [some_id]
        SET @index = @index + 1 
        END
    select * from @tab