从一个值中减去多个值

时间:2017-07-31 13:11:59

标签: mysql sql

我必须保持库存的老化,我必须在库存部门显示一个产品的数量待定多少天......

它将以先到先得的方式减去......

Department  |Product  | Date               | Quantity  |Indicator
------------+---------+--------------------+-----------+---------
D001        |P001     | 1Jul2017           | 1000      |ADD
D001        |P001     | 10Jul2017          | 2000      |ADD
D001        |P001     | 15Jul2017          | 3000      |ADD
D001        |P001     | 18Jul2017          | 5500      |SUBTRACT
D001        |P002     | 12Jul2017          | 3000      |ADD
D001        |P002     | 14Jul2017          | 2000      |ADD
D001        |P002     | 15Jul2017          | 4000      |SUBTRACT

最终输出应该是这样的。如果今天的日期是2017年7月31日

Department  |Product  | Date               | Quantity  |AgeinginDays
------------+---------+--------------------+-----------+---------
D001        |P001     | 15Jul2017          | 500       |16
D001        |P002     | 14Jul2017          | 1000      |17

2 个答案:

答案 0 :(得分:2)

可以使用聚合函数和datediff

select Department
  , Product
  , max(Date)
  , sum ( case when indicator =  'ADD' then quantity else -quantity end)
  , datediff(curdate(), max(Date))
from my_table
group by  Department, Product

或者如果您需要按照chillysapiens的建议添加日期

select Department
  , Product
  , t.max_add_date
  , sum ( case when indicator =  'ADD' then quantity else -quantity end)
  , datediff(curdate(), max(t.max_add_date))
from my_table
inner join  (
    select Department
      , Product
      , max(Date) max_add_date
    from my_table 
    where indicator = 'ADD'
    group by  Department, Product
 ) t 
group by  Department, Product

答案 1 :(得分:0)

对于oracle;

SELECT 
 department,
 product,
 max(CASE WHEN "Indicator" LIKE 'Add%' THEN "Date" END) AS "Date",
 sum(CASE WHEN stock."Indicator" LIKE 'Add%' THEN (QUANTITY) ELSE (QUANTITY*-1) END) AS "QUANTITY",
 FLOOR((SYSDATE - max(CASE WHEN "Indicator" LIKE 'Add%' THEN "Date" END))) AS AgeinginDays
FROM STOCK
GROUP BY department,product