0

我有一个名为 #info 的表,如下所示:

name        start        delta
 n1         200.0         43.0
 n2        6000.0         87.0
 n3         739.0        129.0

create table #info (name sysname, startV float, changeV float);

但我需要创建一个表,该表从 #info 表中获取值并计算上表中每个名称的未来值。所以我们有一个起始值和一个数量变化或增量数量。所以我需要生成一个计算未来日期和未来金额的表格。该日期将增加 2 周,并在未来增加一年。在 2013 年 1 月 4 日,我们从 STARTV 值开始,并通过更改值增加起始值。所以基本上,输出将如下所示:

    date        name        amount
01/04/2013      n1           200
01/18/2013      n1           243
02/01/2013      n1           286
 .......        ...          ....
01/04/2014      n1           673
01/04/2013      n2           6000       
01/18/2013      n2           6087
02/01/2013      n2           6174
 .......        ...          ....
01/04/2014      n2           6957
01/04/2013      n3           739   
 .......        ...          ....

这是我到目前为止提出的 SQL 代码,它只针对 n1 值,它没有列出 n2 或 n3 的值...我需要更改什么?

DECLARE @dd DATE
SET @dd = '01/04/2013';
SELECT TOP 24 DATEADD(week, 2*rn, @dd) ,*
    FROM (SELECT rn=(ROW_NUMBER() OVER (ORDER BY name)) -1
       FROM sys.columns ) c cross apply  
 (select d.dbname , d.startV+((rn+1)*d.changeV) as mm from #info d)  a
4

1 回答 1

2
;with cte as (
    select convert(date, '20130401', 112) as Date, i.name, i.startV as amount, 1 as num
    from #info as i

    union all

    select dateadd(wk, 2, c.date) as Date, c.name, c.amount + i.changeV, c.num + 1 as num
    from cte as c
        inner join #info as i on i.name = c.name
    where c.num < 24
)
select *
from cte
order by name asc, date asc

SQL 提琴示例

于 2013-07-29T18:53:48.477 回答