SQL借方,贷方,余额

时间:2015-01-30 13:01:44

标签: mysql sql

嗨我想弄清楚我应该用什么SQL语句来产生这个输出。我尽我所能,但我的查询没有用。感谢

STUDNO  | DEBIT  | CREDIT | BALANCE
1001    | 10000  |        | 10000
1001    |        |  5000  | 5000
1001    | 50     |        | 5050
1002    | 50     |        | 50
1003    | 0      | 0      |0 


these are the tables.

TBLSTUDENTS
ID   | NAME
1001 | A
1002 | B
1003 |



TBLPAYABLES
ID | Studno | Partic| Amount
1  | 1001   | TF    | 10,000
2  | 1001   | ID    | 50     
3  | 1002   | ID    |50

TBLPAYMENTS
ID | Studno  | Amount
1  | 1001    | 5000  

1 个答案:

答案 0 :(得分:0)

这应该这样做

select S.Studno, credit, Debit, row_number() Over (Partition by S.Studno, Order By ID as RN into #A
From
(
select S.Studno, null as credit, D.Amount as Debit
from TBLSTUDENTS S
left join  TBLPAYABLES D
union all
select S.Studno, C.Amount as credit, null as Debit, D.ID
left Join  TBLPAYMENTS C   
union all
select S.Studno, 0 as credit, 0 as Debit, 0
from TBLSTUDENTS S
where S.Studno not in (select Studno from TBLPAYABLES) or 
S.Studno not in (select Studno from TBLPAYMENTS)
) x

select S.Studno, Credit, Debit, C.ID        
( SELECT SUM(Coalesce(Debit,0) - Coalesce(Credit,0)) 
  FROM #A B
  WHERE A.Studno = B.Studno AND B.RN <= A.RN
) PrevSum
From #A A
order by S.Studno, RN