我必须准备总帐报告
masster.Account_Id,masster.Account_Type,masster.Account_Description,@Opening_Ball as openingbal, s.Referencenumber as Referencenumber ,s.Entrydate,isnull( s.debit,0) as Debit,isnull( s.credit,0) as Credit,case
when masster.Account_Type='Accumulated Depreciation' and row_number() over (partition by masster.Account_Id order by masster.Account_Id)=1 THEN SUM(@Opening_Ball+isnull(s.Credit,0) - isnull(s.debit,0)) OVER (ORDER BY s.Entrydate
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW )
when masster.Account_Type='Accumulated Depreciation' and row_number() over (partition by masster.Account_Id order by masster.Account_Id)<>1 THEN SUM(isnull(s.Credit,0) - isnull(s.debit,0)) OVER (ORDER BY s.Entrydate
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW)
when masster.Account_Type='Accounts Payable' and row_number() over (partition by masster.Account_Id order by masster.Account_Id)=1 THEN SUM(@Opening_Ball+isnull(s.Credit,0) - isnull(s.debit,0)) OVER (ORDER BY s.Entrydate
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW)
when masster.Account_Type='Accounts Payable' and row_number() over (partition by masster.Account_Id order by masster.Account_Id)<>1 THEN SUM(isnull(s.Credit,0) - isnull(s.debit,0)) OVER (ORDER BY s.Entrydate
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW)
when
else
case
when row_number() over (partition by masster.Account_Id order by masster.Account_Id) = 1 then
SUM(@Opening_Ball+isnull(s.debit,0) - isnull(s.Credit,0)) OVER (ORDER BY s.Entrydate
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW )
else
SUM(isnull(s.debit,0) - isnull(s.Credit,0)) OVER (ORDER BY s.Entrydate
ROWS BETWEEN UNBOUNDED PRECEDING
AND CURRENT ROW ) end end AS Balance
FROM sometables
输出应为
期初余额:50
id debit credit Balance
1 10 0 60
2 0 20 40
3 60 0 100
总计70 20 50
但是现在结果是期初余额未与其他行正确添加
期初余额:50
id debit credit Balance
1 10 0 60
2 0 20 90
3 60 0 200
toal 70 20 50