我正在使用SQL Server 2008.我有一个表AdvanceEntry
。
--------------------------------------------------------------------------------
Code | PaidDate | Amount | ReceiveDate | ReceiveAmount
--------------------------------------------------------------------------------
102 | 15-04-2004 | 3000 | 20-04-2004 | 2000
104 | 23-05-2006 | 1000 | NULL | 0.00
104 | 25-05-2005 | 1500 | 12-06-2005 | 500
当任何人点击贷款时,贷款金额存储在Amount
列中,日期存储在PaidDate
中,人员代码存储在Code
列中。当该人回馈金额时,该金额将存储在ReceiveAmount
中,而日期则会存储在ReceiveDate
中。
现在我想创建一个类似特定代码的分类帐的报告。
例如代码102
----------------------------------------------------------------------------
PaidDate / ReceiveDate | Amount | ReceiveAmount | Balance
----------------------------------------------------------------------------
15-04-2004 | 3000 | 0 | 3000
20-04-2004 | 0 | 2000 | 1000
代码104
----------------------------------------------------------------------------
PaidDate / ReceiveDate | Amount | ReceiveAmount | Balance
----------------------------------------------------------------------------
23-05-2006 | 1000 | 0 | 1000
25-05-2005 | 1500 | 0 | 2500
12-06-2005 | 0 | 500 | 2000
我该怎么做?请帮帮我..谢谢
答案 0 :(得分:1)
这是一种方法:
with Paid as
(
select Code
, PaidDate
, Amount
from AdvanceEntry
where PaidDate is not null
), Received as
(
select Code
, ReceiveDate
, ReceiveAmount
from AdvanceEntry
where ReceiveDate is not null
), Details as
(
select Code = coalesce(p.Code, r.Code)
, CodeDate = coalesce(p.PaidDate, r.ReceiveDate)
, Amount = sum(p.Amount)
, ReceiveAmount = sum(r.ReceiveAmount)
from Paid p
full join Received r on p.PaidDate = r.ReceiveDate and p.Code = r.Code
group by coalesce(p.Code, r.Code)
, coalesce(p.PaidDate, r.ReceiveDate)
)
select d.Code
, PayReceiveDate = d.CodeDate
, Amount = isnull(d.Amount, 0.0)
, ReceiveAmount = isnull(d.ReceiveAmount, 0.0)
, Balance = isnull(b.Balance, 0.0)
from Details d
outer apply (select Balance = sum(isnull(b.Amount, 0.0) - isnull(b.ReceiveAmount, 0.0))
from Details b where d.Code = b.Code and d.CodeDate >= b.CodeDate) b
order by d.Code, d.CodeDate
您的数据看起来也有轻微的错误;我在小提琴中稍微改了一下以获得预期的结果。
另外值得一提的是,如果您每个代码每天只能获得一次付费/接收操作,那么您可以在查询中没有任何GROUP BY
的情况下离开。
答案 1 :(得分:0)
试试这个(未经测试):
;with cte as (
select Code, PaidDate as Date, Amount as Dr, 0 as Cr, Amount as Net
from Data where PaidDate is not null
union all
select Code, ReceivedData as Date, 0 as Dr, -ReceivedAmount as Cr, -ReceivedAmount as Net
from Data where ReceivedDate is not null
)
select
t1.*, sum(t2.Net) as Balance
from cte as t1
left join cte as t2 on t2.Code = t1.Code and t2.Date <= t1.Date
group by
t1.Code, t1.Date
having t1.Code = @Code