我有3個表格,分別是賬戶,支付,報表。表帳戶具有所有帳戶,表付款具有對該帳戶進行的所有付款,表格帳單具有帳戶的所有報表數據。我如何計算兩個日期之間作出的PaidAmount的總和
帳戶
的AccountID | DateOfDeath |
1001 | 2014-03-10 |
付款
的AccountID | PaidAmount | PaymentDate
1001 | 80.27 | 2014-07-09
1001 | 80.27 | 2014-06-10
1001 | 80.27 | 2014-05-12
1001 | 80.27 | 2014-04-13
1001 | 80.27 | 2014-03-15
1001 | 80.27 | 2014年2月14日
聲明
的AccountID |平衡|聲明日期
1001 | 0.00 | 2014-03-28
1001 | 1909.31 | 2014-02-25
我需要知道2014年2月28日和2014年2月25日的StatementDate(表語句)之間Payments表中PaidAmount(表支付)的總和。 PaidAmount的總和應該是80.27,但我得到了321.08。任何人都可以告訴我我做錯了什麼,或者我怎樣才能以更好的方式編寫查詢?
這裏是我迄今爲止
create table #temp1
(
AccountID Numeric(9, 0)
, DateOfDeath date
, StatementDate date
, Balance numeric(17,2)
)
insert into #temp1
(
AccountID, DateOfDeath, StatementDate, Balance
)
select a.AccountID
,DateofDeath
,StatementDate
,Balance
from Accounts a
inner join Statements b on a.accountID = b.accountID
where StatementDate in (select top 1 statementdate
from Statements
where AccountID = a.AccountID
and StatementDate >= DateOfDeath
order by StatementDate)
Order By a.AccountID, StatementDate
create table #temp2
(
AccountId Numeric(9,0)
, PaidAmount Numeric(10, 2)
, PaymentDate date
)
select a.accountid, sum(a.Paidamount), max(a.PaymentDate)
from tblCreditDefenseInceptionToDateBenefit a
inner join #temp1 b on a.accountid = b.accountid
where a.paymentdate <= (select top 1 StatementDate from Statements
where AccountID = a.accountid
and statementdate >= b.dateofdeath
order by StatementDate desc)
and a.paymentdate > (select top 1 StatementDate from Statements
where AccountID = a.accountid
and statementdate < b.dateofdeath
order by StatementDate desc)
group by a.accountid
order by a.accountid desc
select * from #temp2
drop table #temp1
drop table #temp2