使用sql处理负值

时间:2012-06-07 23:04:04

标签: sql sql-server sql-server-2008 tsql

我有一个数据集,列出了未来产品库存的日期和数量。有时我们的需求超过了我们未来的供应量,我们最终会出现负面的未来数量。我需要将未来的负数量计入以前的供应量,因此我们不会通过过度供应来加剧问题。

在下面的数据集中,我需要通过在链上应用负数量来准备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"

2 个答案:

答案 0 :(得分: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]

答案 1 :(得分: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