需要帮助从表创建分类帐

时间:2016-03-23 05:25:21

标签: sql-server sql-server-2012

每个人......我只是坚持我有两张桌子的场景。 First Table是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

我希望通过加入上面的两个表来输出如下所示。应该从每一行的工资额中减去总金额。

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

4 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分:0)

您可以使用以下查询来获取所需的结果

{{1}}

答案 3 :(得分: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