用视图计算mysql中的运行平衡

时间:2014-02-13 12:27:19

标签: mysql sql select

我的简单表名为ass_material,其中包含以下列:

mat_id    mat_name  supplier    request    stock_received   date 
1           alloy      test       30         0             feb13
2           alloy      test       30         10            feb14
3           alloy      test       30         20            feb14 

我如何生成它或将其计算为: 当stock_balance和请求匹配时,它还会生成“完整”状态。

  mat_id    mat_name  supplier    request    stock_received  Stock_balance   date    status
    1           alloy      test       30         0                 0        feb13
    2           alloy      test       30         10               10        feb14
    3           alloy      test       30         20               30        feb14   complete

这是我的其他视图中的参考代码: 我怎样才能将它调整到上面我想要的输出中?

SELECT m.`mat_id`, m.`mat_name`, m.`request`, m.`stock_receieved`,
       (select sum(stock_received) - sum(stock_received)
        from material m2
        where m2.mat_name = m.mat_name and
              m2.mat_id <= m.mat_id
       ) as Stock_balance,
      m.`date`,
      s.`sup_name`
FROM `material` m
LEFT JOIN `supplier` s on s.sup_id = m.supplier_id
ORDER BY m.`mat_id` ASC;

1 个答案:

答案 0 :(得分:0)

如果stock_balance只是stock_received的总和,那么在子查询中使用它:

SELECT m.`mat_id`, m.`mat_name`, m.`request`, m.`stock_receieved`,
       (select sum(stock_received)
        from material m2
        where m2.mat_name = m.mat_name and
              m2.mat_id <= m.mat_id
       ) as Stock_balance,
       (case when (select sum(stock_received)
                   from material m2
                   where m2.mat_name = m.mat_name and
                         m2.mat_id <= m.mat_id
                  ) = request
             then 'Complete'
             else 'Incomplete'
        end) as status,
      m.`date`,
      s.`sup_name`
FROM `material` m LEFT JOIN
     `supplier` s
     on s.sup_id = m.supplier_id
ORDER BY m.`mat_id` ASC;