我有一个查询,它返回按月分组的总余额(借方 - 贷方)。有4列;
答案 0 :(得分:0)
没有表格架构,示例数据或所需结果......如下所示:
使用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
使用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