如何在一次查询中从购买数量中减去销售数量? [复制]
Posted
技术标签:
【中文标题】如何在一次查询中从购买数量中减去销售数量? [复制]【英文标题】:How to subtract sale quantity from purchase quantity in one query? [duplicate] 【发布时间】:2013-09-16 12:29:58 【问题描述】:我有两个疑问:
str = "select sum(Quantity) from AddStock where ProductId=" +id.ToString() + " AND Type IN('Purchase','StockInward','Sale Return') AND EntryMode='Godown'";
Qty = dc.Retrieve_Datareader(str);
str = "select sum(Quantity) from AddStock where ProductId=" +id.ToString() + " AND Type IN('StockOutward','Sale','Wastage','Purchase Return') AND EntryMode='Godown'";
Qty1 = dc.Retrieve_Datareader(str);
return(Qty - Qty1);
如何将以上两个查询写在一个查询中并得到区别?
【问题讨论】:
【参考方案1】:您可以一次查询多个表。
查询:
SELECT SUM(as1.Quantity) AS SR,
SUM(as2.Quantity) AS PR,
SUM(as1.Quantity) - SUM(as2.Quantity) AS Difference
FROM AddStock as1, AddStock as2
WHERE as1.ProductId = @ProductId
AND as2.ProductId = as1.ProductId
AND as1.Type IN ('Purchase','StockInward','Sale Return')
AND as2.Type IN ('StockOutward','Sale','Wastage','Purchase Return')
AND as1.EntryMode = 'Godown'
AND as2.EntryMode = as2.EntryMode
代码:
using(var command = new OleDbCommand(query, connection))
command.Parameters.AddWithValue("@ProductId", id);
using(var reader = command.ExecuteReader())
if(reader.Read())
var sr = Convert.ToInt32(reader[0]);
var pr = Convert.ToInt32(reader[1]);
var difference = Convert.ToInt32(reader[2]);
【讨论】:
以上是关于如何在一次查询中从购买数量中减去销售数量? [复制]的主要内容,如果未能解决你的问题,请参考以下文章
如何将列表框中列出的产品数量直接减去我的产品数据库? (MySQL的)
SQL Server 2008 R2-查询以获取按月销售的总销售额和数量