加入两个相关的表格

时间:2012-12-17 11:26:11

标签: sql sql-server tsql join

我有两个表:一个用于发票,另一个用于付款:

tbl_Invoice

Invoice

tbl_payment

Payment

欲望输出如下:

PSUM        IPRICE
----------- ------------
312.00      1100.00

其中:

PSUM是付款总额。

IPRICE是该客户的Total_price总和。

我试过的查询是:

select 
IsNull(sum(p.amt), 0) PSUM,
IsNull(sum(i.total_price), 0) IPRICE
from tbl_invoice i
left join tbl_payment p
on i.invoice_id = p.invoice_id
    and i.client_id = p.client_id
where i.client_id = 5
group by i.invoice_id
order by i.invoice_id

但它输出错误:

PSUM        IPRICE
----------- ------------
312.00      400.00
0.00        1000.00

1 个答案:

答案 0 :(得分:1)

好像你想要这个。这给出了amttotal_price的总和,没有分组。您的版本分组由invoice_id组成,区别在于:

select 
  IsNull(sum(p.amt), 0) PSUM,
  IsNull(sum(distinct i.total_price), 0) IPRICE
from tbl_invoice i
left join tbl_payment p
  on i.invoice_id = p.invoice_id
  and i.client_id = p.client_id
where i.client_id = 5

请参阅SQL Fiddle with Demo

你可以写这个的另一种方法是使用子查询:

select 
  IsNull(sum(p.amt), 0) PSUM,
  IsNull(sum(i.total_price), 0) IPRICE
from
(
  select sum(total_price) total_price, invoice_id, client_id
  from tbl_invoice
  group by invoice_id, client_id
) i
left join
(
  select sum(amt) amt, invoice_id, client_id 
  from tbl_payment
  group by invoice_id, client_id
) p
  on i.invoice_id = p.invoice_id
  and i.client_id = p.client_id
where i.client_id = 5

请参阅SQL Fiddle with Demo

两者产生相同的结果:

| PSUM | IPRICE |
-----------------
|  312 |   1100 |