0

我有一个基本表 FoodSales,其中有 3 列 SaleForDay decimal (10,2), SalesToDate decimal (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 + Current SaleforDay 值。

来帮忙。

创建表#FruitSales
(
   SaleForDay 十进制 (10, 2),
   SalesToDate DECIMAL (10, 2),
   ItemOrder INT
);

插入#FruitSales(SaleForDay、SalesToDate、ItemOrder)
值('4.99','4.99','1'),
       ('12.99', NULL, '2'),
       ('14.99', NULL, '3'),
       ('5.99', NULL, '4');

从#FruitSales中选择*;

删除表#FruitSales;

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

4

2 回答 2

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
于 2012-11-13T02:36:10.633 回答
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;
于 2012-11-13T02:37:16.677 回答