sql update int column基于以前的int列

时间:2012-11-13 02:05:28

标签: sql-server-2008

我有一个基本表FoodSales,其中有3列SaleForDay十进制(10,2),SalesToDate十进制(10,2),ItemOrder Int

数据就像这样

SaleForDay|SalesToDate|ItemOrder
4.99|4.99|1  
12.99||2
14.99||3
5.99||4

我正在尝试获得结果

SaleForDay|SalesToDate|ItemOrder
4.99|4.99|1  
12.99|17.98|2
14.99|32.97|3
5.99|38.96|4

此处的方法是SalesToDate =上一个itemorder SalesToDate +当前SaleforDay值。

帮忙。

CREATE TABLE #FruitSales
(
   SaleForDay    DECIMAL (10, 2),
   SalesToDate   DECIMAL (10, 2),
   ItemOrder     INT
);

INSERT INTO #FruitSales (SaleForDay, SalesToDate, ItemOrder)
VALUES ('4.99', '4.99', '1'),
       ('12.99', NULL, '2'),
       ('14.99', NULL, '3'),
       ('5.99', NULL, '4');

SELECT * FROM #FruitSales;

DROP TABLE #FruitSales;

感谢您的帮助,我意识到这可能很简单。

2 个答案:

答案 0 :(得分:0)

试试这个:

;WITH CumulativeData AS
(
SELECT b.ItemOrder, SUM(a.SaleForDay) AS TotalSales
  FROM #FruitSales a INNER JOIN #FruitSales b
    ON a.ItemOrder <= b.ItemOrder
 GROUP BY  b.ItemOrder
)
UPDATE a
SET a.SalesToDate =  TotalSales 
  FROM #FruitSales a INNER JOIN CumulativeData  b
    ON a.ItemOrder = b.ItemOrder;

另一种选择:

UPDATE a
SET SalesToDate = TotalSales 
  FROM #FruitSales a CROSS APPLY 
       (SELECT SUM(SaleForDay) TotalSales FROM #FruitSales b WHERE b.ItemOrder <= a.ItemOrder) b

答案 1 :(得分:0)

CREATE TABLE #FruitSales
(
   SaleForDay    DECIMAL (10, 2),
   SalesToDate   DECIMAL (10, 2),
   ItemOrder     INT
);

INSERT INTO #FruitSales (SaleForDay, SalesToDate, ItemOrder)
VALUES ('4.99', '4.99', '1'),
       ('12.99', NULL, '2'),
       ('14.99', NULL, '3'),
       ('5.99', NULL, '4');

update f
SET SalesToDate = (select sum(saleforday) from #FruitSales ff where ff.itemorder <= f.itemorder)
from #FruitSales f

SELECT * FROM #FruitSales;