当目标表具有主键时,如何从其他表插入数据?

时间:2016-06-01 06:33:59

标签: sql sql-server-2014

我需要帮助创建一个表格,可以跟踪2010-2016年度每年2%的价格上涨。我的create语句如下:

enter image description here

我有24个产品和我的Products表中的起始价格需要插入到我的新表中。理论上我应该有192条记录。我需要填写年份列的帮助,以便它可以循环到2010-2016每个产品。我还需要帮助参考下一年计算的上一年价格。

[enter image description here]

[enter image description here}

1 个答案:

答案 0 :(得分:0)

   with product as 
       ( select 1 as productid , 
                100.0 as price),
        years(year) AS
        (
            SELECT 2011 UNION ALL SELECT 2012 UNION ALL  
            SELECT 2013 UNION ALL SELECT 2014 UNION ALL 
            SELECT 2015 UNION ALL SELECT 2016
        )           
        select 
          p.productid, 
           y.year,
           power(1.02 ,  row_number () over (partition by p.productid order by y.year)) * p.price  currYearPrice,
           power(1.02 ,  row_number () over (partition by p.productid order by y.year)-1) * p.price lastYearPrice     
         from product  p
         cross join years  y

结果是:

pID Year    CurrYPr LasYPr
1   2011    102.000 100.000
1   2012    104.000 102.000
1   2013    106.000 104.000
1   2014    108.000 106.000
1   2015    110.000 108.000
1   2016    113.000 110.000