SQL帮助计算打开和关闭余额列

时间:2016-04-27 18:01:24

标签: sql sql-server-2008 sql-server-2008-r2

我正在使用SQL 2008 R2。我有一个包含以下列的小表:

日期 LOCATION1 LOCATION2 LOCATION3

想要计算这两列

期初余额=从0开始,之后等于从上一天的期末余额 收盘余额=期初余额+地点1 +地点2 +地点3

因此,我基本上希望将其吐出一份报告:

DATE |  OPENING_BALANCE  | LOC1   | LOC2    |   LOC3    |  CLOSING_BALANCE
----------------------------------------------------------------------------
1/1     $0.00              $1,000    $1,000       $1,000        $3,000 
1/2     $3,000             $2,000    $2,000       $1,000        $8,000 
1/3     $8,000            ($1,000)  ($4,000)      $500          $3,500 
1/4     $3,500            $10,000   ($5,000)      $20,000       $28,500 
1/5     $28,500 

有没有简单的方法来计算这两列?帮助赞赏!提前致谢

**为草率表示例道歉

1 个答案:

答案 0 :(得分:3)

好的,根据您提供的信息(仅输出而没有表架构),此查询可能适合您:

WITH cte AS
(
SELECT
    [Date],
    Loc1 = Location1,
    Loc2 = Location2,
    Loc3 = Location3,
    DayTotal = Location1 + Location2 + Location3,
    ROWNUM = ROW_NUMBER() OVER (ORDER BY [Date])
FROM
    tbl
)
SELECT 
    DATE = c1.[Date],
    OPENING_BALANCE = ISNULL(c2.OpeningDayTotals, 0),
    LOC1 = c1.Loc1,
    Loc2 = c1.Loc2,
    Loc3 = c1.Loc3,
    CLOSING_BALANCE = ISNULL(c2.OpeningDayTotals, 0) + c1.DayTotal
FROM 
    cte c1
OUTER APPLY
(
    SELECT
        OpeningDayTotals = SUM(c2.DayTotal)
    FROM
        cte c2
    WHERE
        c1.ROWNUM > c2.ROWNUM
) AS c2