繁体   English   中英

目的表有主键时如何插入其他表的数据?

[英]How to insert data from other tables when the destination table has primary keys?

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

在此处输入图片说明

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

[在此处输入图像描述]

[在此处输入图片说明}

   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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM