如何计算累计费用

时间:2015-12-23 07:23:59

标签: sql crystal-reports

我使用sql查询在crystal中生成了一个报告。有以下字段。 | AcctName | Budget | Current Expenses | |-----------|--------|------------------| | salaeries | 234567 | 1234 | | Supplies | 467543 | 3547 |

还有另一栏是累计费用。请告诉我如何计算累计费用。

2 个答案:

答案 0 :(得分:0)

            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

答案 1 :(得分:0)

累积费用是连续费用的总和,通常由给定的时间段决定。

使用CTE或自联接的替代方法是在SQL Server 2012及更高版本中使用带有SUM()等窗口函数的OVER子句。

在这种情况下,您可以将分区参数留空,它将默认为整个集合。

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

了解OVER子句的好处很有用,因为它可以让您轻松地在数据分区上执行窗口函数。

查看https://msdn.microsoft.com/en-us/library/ms189461.aspx了解更多详情和示例。