上个月的余额值为当月的期初余额

时间:2017-04-05 12:40:56

标签: sql-server sql-server-2008 tsql

我有一个查询,它返回按月分组的总余额(借方 - 贷方)。有4列;

  1. ID
  2. 结算余额
  3. 期初余额
  4. 我想要做的是将上个月的余额值计入当月的期初余额值。例如;比方说2月的期末余额值是100.000 $。那么March的开盘价也必须是100.000美元。

    对造型感到抱歉。我很糟糕。这是样本数据。 Here is the sample data.

    我想在3月的 OPEN_BALANCE 单元格中输入 -14.830.707,59 值。

1 个答案:

答案 0 :(得分:0)

没有表格架构,示例数据或所需结果......如下所示:

使用common table expressionouter apply()

;with cte (
  select
      Id
    , MonthDate = dateadd(month, datediff(month, 0, [Date]), 0) /* date datatype */
    , ClosingBalance = sum(debit)-sum(credit)
  from t
  group by 
      Id
    , dateadd(month, datediff(month, 0, [Date]), 0)
)
select
    Id
  , MonthDate
  , Month = datename(month, MonthDate) 
  , ClosingBalance 
  , OpeningBalance = x.OpeningBalance
from cte
  outer apply (
    select top 1
      OpeningBalance = i.ClosingBalance
    from cte as i
    where i.Id = cte.Id
      and i.MonthDate < cte.MonthDate
    order by i.MonthDate desc
  ) as x

使用common table expression row_number()left join

;with cte (
  select
      Id
    , MonthDate = dateadd(month, datediff(month, 0, [Date]), 0) /* date datatype */
    , ClosingBalance = sum(debit)-sum(credit)
    , rn = row_number() over (
        partition by Id 
        order by dateadd(month, datediff(month, 0, [Date]), 0)
        )
  from t
  group by 
      Id
    , dateadd(month, datediff(month, 0, [Date]), 0)
)
select
    cte.Id
  , cte.MonthDate
  , Month = datename(month, cte.MonthDate) 
  , cte.ClosingBalance 
  , OpeningBalance = i.ClosingBalance
from cte
  left join cte as x
    on x.Id = cte.Id
      and x.rn = cte.rn-1