-- sample table
declare @tblCharge table
(
ChargeId int,
[Plan] char,
TotalAmount int
)
declare @tblPayment table
(
PaymentId int,
ChargeId int,
PayAmount int
)
-- sample data
insert into @tblCharge select 1, 'A', 400
insert into @tblCharge select 2, 'B', 200
insert into @tblCharge select 3, 'C', 300
insert into @tblPayment select 1, 1, 100
insert into @tblPayment select 2, 1, 50
insert into @tblPayment select 3, 1, 70
insert into @tblPayment select 4, 1, 120
insert into @tblPayment select 5, 1, 10
insert into @tblPayment select 6, 2, 50
insert into @tblPayment select 7, 2, 70
-- the query
select c.[Plan],
c.TotalAmount - isnull(a.Amt, 0) as Amount,
p.PayAmount as Pay
from @tblCharge c
inner join @tblPayment p on c.ChargeId = p.ChargeId
cross apply
(
select sum(x.PayAmount) as Amt
from @tblPayment x
where x.ChargeId = c.ChargeId
and x.PaymentId < p.PaymentId
) a
order by c.ChargeId, p.PaymentId
你有寫任何代碼了嗎?你能分享你的代碼嗎? – AKS
選擇tblCharge.strCharge [計劃] ,tblCharge.fltChargeAmount-tblPaymentDetail.fltAmount [量] ,tblPaymentDetail.fltAmount [數額支付] 從tblCharge 內部聯接tblPayment上tblCharge.ChargeId = tblPaymentDetail.intChargeId –