如何从SQL Server 2000中的表中提取当前库存

时间:2011-12-20 16:40:04

标签: sql-server-2000

我正在使用Visual Studio 2005和SQL Server 2000在vb.net中制作和应用。我必须跟踪库存。添加库存时其状态设置为“未售出”。当某些股票被移除时,交易将股票的状态保持为“已售出”。对于已过期的股票状态也可以是“已过期”,当向公司索取过期股票时,状态为“已声明”......现在,我想要提取当前库存的库存。在具有两个状态值的基本级别,即“已售出”和“未售出”,我使用以下查询从数据库中提取结果,但它不计算已售出和未售出项目的差异...

 select category, item_name, 
        sum(crtns_added) as Cartons, sum(pieces_added) as Pieces, 
        sum(total_price) 
 from Stock 
 where status = 'unsold' 
 group by category, item_name

我也试过这个

select category, item_name, (sum(crtns_added) - sum(crtns_removed)) as Cartons, 
       (sum(pieces_added)- sum(pieces_removed)) as Pieces, 
       sum(total_price) 
from Stock 
where status = 'unsold' or status = 'sold' 
group by category, item_name

1 个答案:

答案 0 :(得分:0)

您需要使用两个子选项来选择具有适当值的项目 - 例如:

SELECT
    category, 
    item_name, 
    (SELECT SUM(crtns_added) FROM dbo.Stock s1 WHERE s1.ItemID = s.ItemID AND s1.Status = 'unsold') 'Unsold Cartons',
    (SELECT SUM(crtns_added) FROM dbo.Stock s2 WHERE s2.ItemID = s.ItemID AND s2.Status = 'sold') 'Sold Cartons'
 FROM 
    dbo.Stock s
 GROUP BY 
    category, item_name

这假设有itemId列唯一标识您的商品 - 某种主键。使用这种技术,您可以获得已售出或未售出的纸箱或碎片的总和 - 无论您需要什么。