从两张桌子获得派对余额

时间:2012-12-25 06:48:40

标签: sql sql-server sql-server-2008

  

可能重复:
  Show account balance from multiple tables

我有两张表如下

voucherCr

srno    vouchertype voucherprefix   voucherno   crparty cramount
1        PURCHASE       P              1            2   55000
2        PAYMENT        R              1            1   55000

voucherDr

srno    vouchertype voucherprefix   voucherno   drparty dramount
1        PURCHASE       P              1            4   54000
2        PAYMENT        R              1            2   55000
3        PURCHASE       P              1            4       1000 

在这里,在PURCHASE凭证P / 1中,我从第2方价值55000购买商品 在PAYMENT代金券R / 1中,我向第2方支付55000卢比。

现在,如果我查询第2方,我想以下列格式显示信息

VTYPE      VPRE      VNO      AGAINSTPARTY      CREDIT      DEBIT
PURCHASE   P         1        4                 55000       NULL
PAYMENT    R         1        1                 NULL        55000

所以第二方的期末余额将为零,因为我已经支付了55000,而不是购买55000

你能帮助我吗?

更新 我尝试了以下但没有结果

select * from voucherCr vc
full outer join voucherDr vd
on vc.voucherno=vd.voucherno
and vc.voucherprefix=vd.voucherprefix
and vc.vouchertype=vd.vouchertype
where vc.crparty=2 or vd.drparty=2

更新2

如果同一个voucherno和voucherprefix的表中有多个条目,我的结果会出错。

2 个答案:

答案 0 :(得分:1)

我认为你需要这个:

select C.vouchertype,C.voucherprefix,C.voucherno,D.drparty,C.cramount AS CREDIT,NULL as DEBIT
from voucherCr C
inner join voucherDr D on C.vouchertype=D.vouchertype and C.voucherprefix=D.voucherprefix    and C.voucherno=D.voucherno
and C.crparty=2
union
select D.vouchertype,D.voucherprefix,D.voucherno,C.crparty,NULL as CREDIT,D.dramount AS   DEBIT
from voucherCr C
inner join voucherDr D on C.vouchertype=D.vouchertype and C.voucherprefix=D.voucherprefix and C.voucherno=D.voucherno
and D.Drparty=2

答案 1 :(得分:0)

`SELECT *   
 FROM voucherCr VC  
   FULL OUTER JOIN voucherDr VD ON VC.crparty = VD.drparty  
 WHERE  
   (VC.crparty IS NULL OR VD.drparty IS NULL)`

示例:http://www.sqlfiddle.com/#!3/74419/45