SQL Server:我们想从相同字段的两个表中获取不同字段数量的记录吗?

时间:2017-09-26 14:59:32

标签: sql sql-server

我们有三个表A,B,C。一个包含主信息的表,B表包含计费信息,C表包含收到的信息。

现在当我开帐单时,数据被插入到B表中,当收到付款时,数据被插入到C表中。所以现在如果客户只支付了一半的付款,那么支付条目就会进入C表,但是当我选择客户时,它会在列表中显示两次,并且上次输入详细信息。

查询:

select 
    CONVERT(varchar(10), p.PurDate, 103) PurDate,
    p.PurchaseNo, s.ClientID, s.SrNo, s.Ledger,
    p.Total, p.InvoiceTotal as PurchaseAmount,
    ISNULL(purecord.paidamt, 0) as paidamt,
    (p.InvoiceTotal - paidamt) as BalanceAmount,
    p.CompanyID, p.branchid1, p.finyearid
from 
    A as s
inner join 
    B as p on s.SrNo = p.SuppLedID
left join 
    (select 
         SUM(Purlamt) as paidamt, lid_rowid, Purno
     from 
         C
     group by 
         lid_rowid, Purno) as purecord on purecord.Purno = p.PurchaseNo
where 
    not exists (select *
                from C
                where p.InvoiceTotal = paidamt)

结果

PurDate PurchaseNo ClientID SrNo      Ledger       Total PurchaseAmount paidamt BalanceAmount
23/08/2017      43  2   SUP00002    OM COMPUTERS    4055    4055    4000    55
23/08/2017      43  2   SUP00002    OM COMPUTERS    4055    4055    165    3890

但是我们期待它应该在下面的第二个条目

PurDate PurchaseNo ClientID SrNo      Ledger       Total PurchaseAmount paidamt BalanceAmount
23/08/2017      43  2   SUP00002    OM COMPUTERS    4055    4055    4055    0

0 个答案:

没有答案