php - mysql 总库存库存

标签 php mysql sql

如果您不介意的话,我还有一个关于我的问题的后续问题..

count total flow inventory in and out php mysql

Table A
=======================================================
**id** | **code** | **status** | **total** | **date** |
1      | B01      | IN         | 500       |2013-01-15|
2      | B01      | OUT        | 100       |2013-01-20|
3      | B01      | OUT        | 200       |2013-02-01|
4      | B01      | IN         | 300       |2013-02-05|

从上表中我想要这样的输出..

Table A
===================================================================================
**id** | **code** | **status** | **total** | **date** | **stock** | 1st month stock
1      | B01      | IN         | 500       |2013-01-15| 500       | -
2      | B01      | OUT        | 100       |2013-01-20| 400       | 500
3      | B01      | IN         | 200       |2013-02-01| 600       | 400
4      | B01      | OUT        | 300       |2013-02-05| 300       | 600
5      |          |            |           |          |           | 300

如何使用 mysql 实现这一点?有办法吗?

对于股票专栏,我已经使用这种方法实现了

select t.*, @stock := @stock + case when status = 'IN' 
                                    then total
                                    else -total  
                               end as stock
from your_table t
cross join (select @stock := 0) s
order by t.id

来 self 的previous question ,帮帮我,我对 mysql 很陌生

最佳答案

根据您已有的内容,您可以向 SELECT 列表添加另一个表达式,

select t.*, @stock AS `1st month stock`, @stock := ...

注意在将新值分配给 SELECT 列表中的 @stock 之前,需要返回 @stock 的当前值,因此列的顺序略有不同比所需输出中显示的要多。

<小时/>

根据您当前的查询,只需将新表达式添加到您的 SELECT 列表中,即可返回另一列,例如

select t.*
     , @stock AS `1st month stock`
     , @stock := @stock + case when status = 'IN' 
                                then total
                                else -total  
                           end as stock
from your_table t
cross join (select @stock := 0) s
order by t.id

关于php - mysql 总库存库存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24369924/

相关文章:

PHP:处理未定义数组键的最快方法

PHP XMLReader 获取所有节点名称

mysql - Mysql集群安装完成后启动Mysql

php - 我在为图像创建单独的表时遇到问题

php - 关于允许用户向 mysql 数据库提交信息的指南

php mysql查询 - 查询中变量的输出值

MySQL条件插入导致错误代码1364 : "Field doesn' t have a default value"

SQL Server 网址解码

sql - 复杂的 Rails 查询 - 联合?子选择?我还能使用 named_scope 吗?

javascript - jQuery split() 返回未定义