简体   繁体   English

如何计算累积费用

[英]How to Calculate Cumulative expenses

I have generated a report in crystal using sql query.我已经使用 sql 查询在水晶中生成了一份报告。 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.使用 CTE 或自联接的替代方法是将 OVER 子句与窗口函数(如 SQL Server 2012 及更高版本中的 SUM())一起使用。

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.了解 OVER 子句的好处很有用,因为它可以让您轻松地对数据分区执行窗口函数。

Check out https://msdn.microsoft.com/en-us/library/ms189461.aspx for more details and examples.查看https://msdn.microsoft.com/en-us/library/ms189461.aspx了解更多详细信息和示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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