Query for total should keep on adding with each row of cost Column

泄露秘密 提交于 2019-12-12 15:07:25

问题


I have table with columns as

      Operation             Cost

     Material Issue         10 
     Material Return        20
     X                      30
     Y                      40
     Z                      50

I want want a query where columns are

     Operation             Cost    Total

     Material Issue         10      10
     Material Return        20      30
     X                      30      60
     Y                      40      100
     Z                      50      150

ie.., the the total should keep on adding with each row of cost Column


回答1:


try this

DECLARE @Table TABLE(
        ID INT IDENTITY(1,1),
        Descr VARCHAR(20),
        Val FLOAT
)

INSERT INTO @Table (Descr,Val) SELECT 'X', 10
INSERT INTO @Table (Descr,Val) SELECT 'Y', 20
INSERT INTO @Table (Descr,Val) SELECT 'Z', 50
INSERT INTO @Table (Descr,Val) SELECT 'A', 75
INSERT INTO @Table (Descr,Val) SELECT 'B', 100

SELECT  t1.Descr,
        t1.Val,
        SUM(ISNULL(t2.Val,0))
FROM    @Table t1 LEFT JOIN
        @Table t2 ON t1.ID >= t2.ID
GROUP BY    t1.Descr,
            t1.Val



回答2:


There are different ways to calculate running totals. This article on SQLTeam covers them and will help you get your query done. The code examples there are easy adaptable, so I let you choose the one which best fits your needs.



来源:https://stackoverflow.com/questions/1124317/query-for-total-should-keep-on-adding-with-each-row-of-cost-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!