如何对prev列中的值求和以为下一列创建新值

时间:2017-08-11 09:15:21

标签: sql sql-server

CLICK THE IMAGE PLEASE Link to Image

请参阅上图,向您展示我想要做的一个示例。谢谢大家。

我有一个包含销售数据的销售列,我想创建一个新的预测列并在此情况下在销售列已结束的位置启动它472031 + 34546.参见示例

销售栏

34546
56497
89245
122952
160134
187809
227312
264421
308869
342777
388785
430483
472031

最新的销售数字是472031,加上34546,然后下面的列将是506,576,依此类推。

请参阅下面的示例。提前谢谢。

销售预测栏

506,576 
541,122 
575,668 
610,213 
644,759 
679,305 
713,850 
748,396 
782,942 
817,487 
852,033 
886,579 
921,124 
955,670 
990,216 
1,024,761 
1,059,307 
1,093,853 
1,128,398 
1,162,944 
1,197,490 
1,232,035 

2 个答案:

答案 0 :(得分:2)

创建脚本

    create table sales(
  id int, 
  sales int);

insert into sales(id, sales) values (1,34546);
insert into sales(id, sales) values (2,56497);
insert into sales(id, sales) values (3,89245);
insert into sales(id, sales) values (4,122952);
insert into sales(id, sales) values (5,160134);
insert into sales(id, sales) values (6,187809);
insert into sales(id, sales) values (7,227312);
insert into sales(id, sales) values (8,264421);
insert into sales(id, sales) values (9,308869);
insert into sales(id, sales) values (10,342777);
insert into sales(id, sales) values (11,388785);
insert into sales(id, sales) values (12,430483);
insert into sales(id, sales) values (13,472031);

查询

示例1

select sales.sales, (id *34546)+472031 from sales;

<强>例2

WITH CTE AS (
  SELECT
    rownum = ROW_NUMBER() OVER (ORDER BY id),
    (((ROW_NUMBER() OVER (ORDER BY id)) - 1)  * 34546) as extraSales
  FROM sales
)
SELECT
  472031 + cur.extraSales
FROM CTE cur
INNER JOIN CTE prev on prev.rownum = cur.rownum - 1

SQL Fiddles

http://sqlfiddle.com/#!6/4bca1/9

http://sqlfiddle.com/#!6/4bca1/30

答案 1 :(得分:-1)

要计算新的销售额,您可以

select s.*,
       (case when sales = 0
             then row_number() over (partition by sales order by period) * 34546
        end) as inc_sales
from sales s;

然后,您想要在之前的日期添加销售。碰巧的是,如果销售额增加,则这是销售额的最大值。结果是:

select s.*,
       ((case when sales = 0
              then row_number() over (partition by sales order by period) * 34546
         end) +
        max(sales) over ()
       ) as forecast
from sales s;