SQL按先前记录字段的数量减少字段

时间:2016-08-09 14:42:31

标签: sql-server tsql select sum

我有一个查询可以提供一些库存结果。查询查看项目编号并使用“连接到库存”表并检索库存量(InStock)

SUM(di.[Count])as Requested,
ISNULL(mt.qty,0) as InStock,

我得到的是这样的结果:

enter image description here

这是正确的,但是,我希望能够做的是将 InStock 的金额减去先前记录中的金额。

enter image description here

我尝试过的,并且显而易见的原因是这不起作用:

(ISNULL(mt.qty, 0) - SUM(di.[Count])) as Inventory,

我正在研究这样的事情,但之前从未使用过Partition或Over:

sum(mt.qty) over (order by di.InventoryNumber asc) as Inventory

下面是我的完整查询:

SELECT ISNUll(mt.cart,'Not Assigned') as Cart,

                   c.ClientName AS Client,

                   di.InventoryNumber AS IMS_Number,

                   SUM(di.[Count])as Requested, 

                   ISNULL(mt.qty,0) as InStock,

                   (ISNULL(mt.qty, 0) - SUM(di.[Count])) as Inventory, 

                    CASE di.IsManual  
                       WHEN 0 THEN 'Auto'
                       WHEN 1 THEN 'Manual'
                     END As Operation,

                     CASE WHEN mt.item IS NULL THEN 'New' ELSE 'In Stock' END as Availability,

                     CASE jl.LocationId 
                        WHEN 0 THEN 'Both'
                        WHEN 1 THEN 'Bond'
                        WHEN 2 THEN 'Woodlands'
                     END AS Location,

                     CAST (di.ItemDescription AS TEXT) as Descriptions,
                     di.ItemType AS [Type]


                         FROM linwdc1f.eFulfillment2.dbo.DailyInventoryView di 

                          INNER JOIN linwdc1f.eFulfillment2.dbo.JobConfigs jc ON di.JobName=jc.JobName 
                          INNER JOIN linwdc1f.eFulfillment2.dbo.Clients c ON di.ClientId=c.ClientId 
                          INNER JOIN linwdc1f.eFulfillment2.dbo.JobLocations jl ON  jl.JobName = di.JobName AND jl.LocationId=2
                          LEFT OUTER JOIN linwdc1f.eFulfillment2.dbo.printjobs pj on pj.JobName =di.JobName
                          LEFT OUTER JOIN linwdc1f.eFulfillment2.dbo.PrintComponents pc on pc.id = pj.PrintComponentId
                          LEFT OUTER JOIN linwdc1f.eFulfillment2.dbo.ProjectJobs prj on prj.id = pc.ProjectJobId
                          LEFT OUTER JOIN Master mt on di.InventoryNumber = mt.item 

                        WHERE di.JobDate BETWEEN '2016-08-08' AND '2016-08-08'  AND prj.ProjectJobName IS NULL

                        GROUP BY c.ClientName, mt.cart, di.InventoryNumber,c.ClientName ,mt.qty,mt.item,jl.LocationId,di.ItemDescription,di.ItemType,di.IsManual
                        Order by di.InventoryNumber,c.ClientName, mt.cart

1 个答案:

答案 0 :(得分:1)

我想你有一个像“RequestID”这样的列来标识你的Request表中的每条记录。请相应地进行修改。

确保使用SQL Server 2012及更高版本,因为我使用的是LAG功能,这是自SS 2012以来的新功能。经过测试,它在SSMS中运行良好。 :)

np.copyto(result, d, where=m)

顺便说一句,在目标结果集中,最后一条记录应该是-8而不是-6。

enter image description here

enter image description here