从以前的记录中减去 - 嵌套查询SQL

时间:2016-06-29 14:59:34

标签: sql subquery

我有如下查询:

select ISNULL(sum(fonhand),0.00) as 'Supply', 0 as 'Demand'
from invoice where ptno = @ptno 
union  
select distinct  a.quantity as 'Supply', 0 as 'Demand'
from jbMstr a join jbDetails b on a.fjobno = b.fjobno
  where a.ptno = @ptno AND a.status = 'RELEASED' AND fbmsource = 'S' 
union
select  0 as 'Supply',  ftotqty as 'Demand'
from jbDetails a join jbMstr b on a.fjobno = b.fjobno
where fbompart = @ptno and fstatus = 'RELEASED' AND fbmsource = 'S'

输出如下:

Supply    Demand       Avail
-4.00000 0.0000000000    -4
0.00000 1.0000000000     -5
0.00000 1.0000000000      -6
0.00000 4.0000000000      -10
0.00000 -1.0000000000     -9

我希望获得新专栏#34; Avail"它应该从" Demand"中减去每行中的列。如何实现这个?

任何人都可以帮我这样做吗? 提前谢谢......

1 个答案:

答案 0 :(得分:1)

使用Running total trick来执行此操作

考虑到您有一列来识别订单

SELECT [supply], 
       [demand], 
       [avail] 
FROM   Yourtable a 
       CROSS apply(SELECT Sum(supply - demand) AS [Avail] 
                   FROM   Yourtable b 
                   WHERE  a.id >= b.id) cs 

Sql Server 2012+中,您可以使用Sum() Over(Order by)窗口函数计算运行总计

SELECT [supply], 
       [demand], 
       Sum(supply - demand)OVER(ORDER BY id) as Avail, 
FROM   Yourtable