繁体   English   中英

如何计算累积费用

[英]How to Calculate Cumulative expenses

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

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

            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

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

使用 CTE 或自联接的替代方法是将 OVER 子句与窗口函数(如 SQL Server 2012 及更高版本中的 SUM())一起使用。

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

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了解更多详细信息和示例。

暂无
暂无

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

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