...このような何か:
:
row_number()
と
left join
と
common table expressionを使用
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
を使用
;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
行データを共有してください。 –