简体   繁体   中英

How to Calculate Cumulative expenses

I have generated a report in crystal using sql query. which have following fields. | AcctName | Budget | Current Expenses | |-----------|--------|------------------| | salaeries | 234567 | 1234 | | Supplies | 467543 | 3547 |

There is another column that is cumulative expenses.Please tell me how to calculate cumulative expenses.

            By implementing following logic in your procedure you will get cumulative expense 
            Create  table   #Temp
            (
            id int identity(1,1),
            AccountName varchar(15),
            Budget numeric(18,0),
            CurrentExpense numeric(18,0)
            )

            insert into #Temp
            select 'salaeries',234567,1234             
            union
            select 'Supplies',467543,3547             
            union
            select 'Maintenance',10000,2000
            union
            select 'Lighting',5000,2000

            select * from #Temp order by Id


            select 
            t1.Id,
            t1.AccountName,
            t1.Budget, 
            t1.CurrentExpense,
            SUM(t2.CurrentExpense) as CumulativeExpense

            from #Temp t1
            inner join #Temp t2 
            on t1.id >= t2.id

            group by 
            t1.Id,
            t1.AccountName,
            t1.Budget, 
            t1.CurrentExpense

            order by t1.id

Cumulative expenses are the sum of successive expenses, usually dictated by a given period of time.

An alternative to using CTE's or self joins is to use the OVER Clause with window functions like SUM() in SQL Server 2012 and above.

In this case you can leave the partition arguments blank and it will default to the entire set.

SELECT    AcctName
        , Budget
        , [Current Expenses]
        , SUM([Current Expenses]) OVER(ORDER BY acctName ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS [Cumulative Expenses]
FROM    #Temp

It is useful to understand the benefits of the OVER Clause as it can allow you to easily perform window functions on partitions of your data.

Check out https://msdn.microsoft.com/en-us/library/ms189461.aspx for more details and examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM