簡體   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