-1
我有一个查询返回按月分组的总余额(借方贷方)。有4列;上个月的余额到当月的期初余额
- ID
- 月
- 期末余额
- 期初余额
我想要做的是让上个月的平衡值到当月的期初余额值。例如;假设2月份的期末余额为100.000 $美元。那么3月份的开盘价也必须是100.000美元。
我想在三月的OPEN_BALANCE细胞-14.830.707,59值。
我有一个查询返回按月分组的总余额(借方贷方)。有4列;上个月的余额到当月的期初余额
我想要做的是让上个月的平衡值到当月的期初余额值。例如;假设2月份的期末余额为100.000 $美元。那么3月份的开盘价也必须是100.000美元。
我想在三月的OPEN_BALANCE细胞-14.830.707,59值。
如果没有表架构,例如数据,或期望的结果......事情是这样的:
使用common table expression和outer 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
使用与row_number()
一个common table expression和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
请分享您的行数据,我们可以尝试 –