使用运行减法运行总计

时间:2018-06-07 08:55:15

标签: sql-server sql-server-2008

我在sql server 2008中的存储过程中使用了运行总计,并且我已经传递了一个id列表。现在的问题是,我得到了所有ID的总和。

我想要的是单独列出列表中传递的ID。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

    create table #t ( Ordid int primary key , Receiptqty int , Issueqty int)

    insert #t(Ordid,Receiptqty,Issueqty)  values (1,2577,0)
    insert #t(Ordid,Receiptqty,Issueqty) values (2,2577,0)
    insert #t(Ordid,Receiptqty,Issueqty)  values (3,7903,0)
    insert #t(Ordid,Receiptqty,Issueqty)  values (4,7893,0)
    insert #t(Ordid,Receiptqty,Issueqty)  values (5,7920,0)
    insert #t(Ordid,Receiptqty,Issueqty)  values (6,7922,0)
    insert #t(Ordid,Receiptqty,Issueqty)  values (7,6903,0)
    insert #t(Ordid,Receiptqty,Issueqty)  values (8,7920,0)
    insert #t(Ordid,Receiptqty,Issueqty)  values (9,7922,0)

    --select * from #t order by Receiptqty 

    -- Running Total for SQL Server 2008 R2 and Earlier Version

    SELECT Receiptqty, Issueqty,
    (SELECT SUM(Receiptqty-Issueqty)
    FROM #t T2
    WHERE T2.Ordid <= t1.Ordid) AS RunningTotal
    FROM #t T1
    GO

    drop table #t