2016-03-23 105 views
2

創建分類帳每個人..我只是堅持情景,我有兩個像下面的表。第一個表是tblCharge和第二個是tblPayment需要幫助從表

chargeId Plan TotalAmount 
1   A  400 
2   B  200 
3   C  300 


PaymentId ChargeId PayAmount 
1   1  100 
2   1  50 
3   1  70 
4   1  120 
5   1  10 
6   2  50 
7   2  70 

我要像下面的輸出由兩個以上table.Total量加入應從每一行的支付金額中扣除。

Plan Amount Pay 
A  400  100 
A  300  50 
A  250  70 
A  180  120 
A  60  10 
+0

你有寫任何代碼了嗎?你能分享你的代碼嗎? – AKS

+0

選擇tblCharge.strCharge [計劃] ,tblCharge.fltChargeAmount-tblPaymentDetail.fltAmount [量] ,tblPaymentDetail.fltAmount [數額支付] 從tblCharge 內部聯接tblPayment上tblCharge.ChargeId = tblPaymentDetail.intChargeId –

回答

0
-- 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 
0

您可以使用下面的查詢來獲得您想要的結果

select chargeid, 
    totalamount-isnull(lag(amount) over(partition by chargeid order by chargeid),0) as amount, 
    payamount as pay 
from (
    select t2.chargeid 
     ,t1.totalamount 
     ,sum(t2.payamount) over (
      partition by t2.chargeid order by t2.paymentid 
      ) as amount, 
      t2.payamount 
    from tblCharge t1 
    join tblpayment t2 on t1.chargeid = t2.chargeid 
    ) a 
0

希望,這個簡單的查詢將解決您的問題。

SELECT C.[Plan],C.TotalAmount - ISNULL((SELECT SUM(PT.PayAmount) FROM tblPayment PT 
    WHERE PT.ChargeId = C.ChargeId AND PT.PaymentId < P.PaymentId),0) Amount,P.PayAmount Pay 
FROM tblCharge C 
INNER JOIN tblPayment P ON P.ChargeId = C.ChargeId 
2

使用SUM OVER()

SQL Fiddle

SELECT 
    c.ChargeId, 
    Amount = TotalAmount 
       - SUM(PayAmount) OVER(PARTITION BY c.[Plan] ORDER BY p.PaymentId) 
       + PayAmount, 
    p.PayAmount 
FROM tblCharge c 
INNER JOIN tblPayment p 
    ON p.ChargeId = c.ChargeId