计算另一个表中每个事务中项的数量
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算另一个表中每个事务中项的数量相关的知识,希望对你有一定的参考价值。
我在股票部门的公司工作考虑两个出口和股票表,其中出口具有以下属性:
Export{
ExportDate Date not null,
StockID int not null,
Quantity decimal(10, 2),
};
和Stock表具有以下属性:
Stock{
ItemID int primary key,
ItemName nvarchar(MAX).
Exist decimal(15, 2)
};
因此,导出表中的StockID是Stock表格中的ItemID引用,也是当一个记录保存在导出表格中时,它还会根据导出表格中的stockID更新库存存量,这些代码在VB.Net的导出表单中保存按钮,如下所示:
Try
cmd = New SqlCommand("INSERT INTO Export(ExportDate,StockID,Quantity) VALUES(@ExportDate, @StockID, @Quantity)", con)
cmd.CommandTimeout = 1000
cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("@StockDate", dateTXT.Text)
cmd.Parameters.AddWithValue("@StockID", comboStockID.SelectedValue)
cmd.Parameters.AddWithValue("@Quantity", quantityTXT.Text)
cmd.ExecuteNonQuery()
MessageBox.show(“Stored”)
Catch ex As Exception
MessageBox.Show(“Not stored!” ex.Message)
End Try
'Updating stock Exist
Try
cmd = New SqlCommand("UPDATE Stock SET Exist = Exist - @quantity
WHERE ItemID = '" & comboStockID.SelectedValue & "'", con)
cmd.Parameters.AddWithValue("@quantity", qtyTXT.Text)
cmd.ExecuteNonQuery()
MessageBox.show(“Updated!”)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
假设股票表格值如下:
ItemID ItemName Quantity
105 Black color 300
106 Green color 400
但是,当我加入它时,每行显示只有300,它选择如下:
ItemID ItemName Quantity
105 Black color 300
106 Green color 300
我想加入Exist of stock with Export table,在每个交易中它必须显示如下:
ExportDate stockID Quantity Exist
2017/8/24 105 5 295
2017/10/30 105 25 270
帮帮我们,我该怎么办!!!
答案
你可以使用windows函数,这是示例代码:
select exportdate, stockid, quantity,
sum(pre_balance) over (partition by stockid order by exportdate) as exist
from
(select exportdate, stockid, quantity, -quantity as pre_balance
from export
union
select '2017-01-01' as exportdate, itemid as stockid,
0 as quantity, exist as pre_balance
from stock
order by exportdate) as sub_query;
这是结果:
exportdate | stockid | quantity | exist
------------+---------+----------+--------
2017-01-01 | 105 | 0 | 300.00
2017-08-24 | 105 | 5.00 | 295.00
2017-10-30 | 105 | 25.00 | 270.00
2017-01-01 | 106 | 0 | 400.00
来源表:
latihan=> select * from stock ;
itemid | itemname | exist
--------+-------------+--------
105 | Black color | 300.00
106 | Green color | 400.00
(2 rows)
latihan=> select * from export ;
exportdate | stockid | quantity
------------+---------+----------
2017-08-24 | 105 | 5.00
2017-10-30 | 105 | 25.00
(2 rows)
这个链接是一个关于windows函数的例子,但在印尼语和postgresql中:
https://github.com/muntaza/Open_Persediaan/blob/master/perhitungan_saldo.md
这是链接到谷歌上的搜索:
https://www.google.com/search?q=windows+function+ms+sql
这个链接关于股票,用英语:
https://callmeranjeet.wordpress.com/2014/09/01/calculating-stock-with-fifo-method-in-sql/
以上是关于计算另一个表中每个事务中项的数量的主要内容,如果未能解决你的问题,请参考以下文章
为啥尽管源代码没有变化,但从一个系统到另一个系统的片段数量却有很大差异?