Handling negative values with sql

后端 未结 2 1177
花落未央
花落未央 2021-01-25 02:42

I have a data set that lists the date and quantity of future stock of products. Occasionally our demand outstrips our future supply and we wind up with a negative future quantit

相关标签:
2条回答
  • 2021-01-25 02:56

    Here is a CROSS APPLY - tested

    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
    
    0 讨论(0)
  • 2021-01-25 03:09

    You don't seem to get a lot of answers - so here's something if you won't get the right 'how-to do it in pure SQL'. Ignore this solution if there's anything SQLish - it's just a defensive coding, not elegant.

    If you want to get a sum of all data with same season why deleting duplicate records - just get it outside, run a foreach loop, sum all data with same season value, update table with the right values and delete unnecessary entries. Here's one of the ways to do it (pseudocode):

    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]
    
    0 讨论(0)
提交回复
热议问题