示例:
假设我有输入库存号是500而数量(销售数量)是5然后剩余库存是495,在下一种情况下,我在输入库存中出售其他项目必须是495而不是500,如果数量是6则489 ..
如何使用sqlserver计算? 这是存储过程:
select i.itemid,i.ItemName,i.EntryDate as 'Purchase Date',i.PurchaseRate as 'Purchase Amount',
s.SaleDate,isnull(s.TotalPrice,0)as 'SalesAmount',sum(i.quantity)as 'Input Stock',s.Quantity,
sum(i.quantity)-sum(ISNULL(s.quantity,0)) as 'Remaining Stock'
from Inv_Medicine i
left join Inv_Sales s on s.itemid=i.itemid
group by i.itemid,i.ItemName,i.EntryDate,i.PurchaseRate,s.SaleDate,s.TotalPrice,s.Quantity
以上查询无法正常工作..有任何建议???
如何减去库存和销售?
我想要而不是500必须是495并且在495之后如果数量是6剩余库存489 ..取决于数据(动态输入库存和数量数据)
答案 0 :(得分:1)
DECLARE @date1 datetime='2017-01-25 04:48:03.830'
DECLARE @date2 datetime='2017-01-26 04:48:03.830'
SELECT t1.*, CurrentStock = (isnull(t1.Quantity,0)-
SUM(isnull(t2.salsesquantity,0)))+isnull(t1.salsesquantity,0),
isnull(t1.salsesquantity,0)
as SalesProductQunatity, RemainingStock = isnull(t1.Quantity,0)-
SUM(isnull(t2.salsesquantity,0))
FROM ( SELECT
im.ItemName,im.PurchaseRate,Ins.SalesDate,ins.totalprice,ins.quantity
as salsesquantity,im.Quantity , ROW_NUMBER()OVER( partition by
Ins.itemId ORDER by ins.SalesDate) as ranknumbr FROM
[dbo].[Inv_Medicine] IM LEFT JOIN [dbo].Inv_Sales Ins on
IM.ItemId=Ins.ItemId ) t1
INNER JOIN
( SELECT
im.ItemName,im.PurchaseRate,Ins.SalesDate,ins.totalprice,ins.quantity
as salsesquantity,im.Quantity , ROW_NUMBER()OVER( partition by
Ins.itemId ORDER by ins.SalesDate) as ranknumbr FROM
[dbo].[Inv_Medicine] IM LEFT JOIN [dbo].Inv_Sales Ins on
IM.ItemId=Ins.ItemId ) as t2
ON t1.ranknumbr >= t2.ranknumbr AND t1.ItemName=t2.ItemName
WHERE t1.SalesDate BETWEEN @date1 AND @date2
GROUP BY
t1.ranknumbr,
t1.SalesDate,t1.ItemName,t1.PurchaseRate,t1.totalprice,t1.salsesquantity,
t1.Quantity,t2. Quantity
ORDER by t1.ItemName DESC
请检查我的回答,它会对你有所帮助。 如果你卡在任何地方,请告诉我。