1

我有一个数据集,列出了未来产品库存的日期和数量。有时,我们的需求超过了我们未来的供应,我们最终会得到一个负的未来数量。我需要将未来的负数量计入之前的供应量,这样我们就不会因超卖供应而加剧问题。

在以下数据集中,我需要为 10 至 19 日的需求做准备,将负数沿链向上应用,直到我得到一个正数:

"ID","SKU","DATE","SEASON","QUANTITY"
"1","001","2012-06-22","S12","1656"
"2","001","2012-07-13","F12","1986"
"3","001","2012-07-27","F12","-283"
"4","001","2012-08-17","F12","2718"
"5","001","2012-08-31","F12","-4019"
"6","001","2012-09-14","F12","7212"
"7","001","2012-09-21","F12","782"
"8","001","2012-09-28","F12","2073"
"9","001","2012-10-12","F12","1842"
"10","001","2012-10-19","F12","-12159"

我需要做到这一点:

"ID","SKU","DATE","SEASON","QUANTITY"
"1","001","2012-06-22","S12","1656"
"2","001","2012-07-13","F12","152"

我已经研究过使用 while 循环和外部应用,但似乎还没有找到一种方法来做到这一点。任何帮助将非常感激。这需要适用于 sql server 2008 R2。

这是另一个例子:

"1","002","2012-07-13","S12","1980"
"2","002","2012-08-10","F12","-306"
"3","002","2012-09-07","F12","826"

会成为:

"1","002","2012-07-13","S12","1674"
"3","002","2012-09-07","F12","826"
4

2 回答 2

0

你似乎没有得到很多答案——所以如果你没有得到正确的“如何在纯 SQL 中做这件事”,这里有一些东西。如果有任何 SQLish,请忽略此解决方案 - 它只是一种防御性编码,而不是优雅的。

如果您想获得具有相同季节的所有数据的总和,为什么要删除重复记录 - 只需将其取出,运行 foreach 循环,对具有相同季节值的所有数据求和,使用正确的值更新表并删除不必要的条目。这是其中一种方法(伪代码):

productsArray = SELECT * FROM products
processed = array (associative)
foreach product in productsArray:
  if product[season] not in processed:
    processed[season] = product[quantity]
    UPDATE products SET quantity = processed[season] WHERE id = product[id]
  else:
    processed[season] = processed[season] + product[quantity]
    DELETE FROM products WHERE id = product[id]
于 2012-06-08T00:17:58.940 回答
0

这是一个CROSS APPLY经过测试的

SELECT b.ID,SKU,b.DATE,SEASON,QUANTITY
FROM (
  SELECT SKU,SEASON, SUM(QUANTITY) AS QUANTITY
  FROM T1 
  GROUP BY SKU,SEASON
  ) a
CROSS APPLY (
  SELECT TOP 1 b.ID,b.Date FROM T1 b
  WHERE a.SKU = b.SKU AND a.SEASON = b.SEASON
  ORDER BY b.ID ASC
  ) b
  ORDER BY ID ASC
于 2012-06-08T00:18:42.683 回答