加入查询需要帮助

时间:2012-12-12 10:13:30

标签: sql-server join

我有两张桌子:

tbl_Invoice

Invoice

tbl_payment

Payment

当我通过client_Id = 5时,所需的输出应为:

PSUM        IPRICE          Amt_Type
----------- -------------- ----------------
100.00      100.00         USD
  0.00      1000.00        GBP

哪里

PSUM是总付款总和

IPRICE是发票总价的总和

我试过的是:

Select SUM(P.Amt) as PSUM, SUM(I.Total_price) as IPRICE, I.Amt_Type  from
[tbl_payment] P left join [tbl_Invoice] I on P.invoice_Id = I.invoice_Id
    WHERE P.client_id = @Client_Id and I.client_id = @Client_Id
    group by I.Amt_Type

1 个答案:

答案 0 :(得分:2)

以下似乎有效:

declare @client_id int = 5

select 
  IsNull(sum(p.amt), 0) PSUM,
  IsNull(sum(i.total_price), 0) IPRICE,
  i.amt_type
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 = @client_id
group by i.amt_type, i.invoice_id
order by i.invoice_id

请参阅SQL Fiddle with Demo

结果:

| PSUM | IPRICE | AMT_TYPE |
----------------------------
|  100 |    100 |      USD |
|    0 |   1000 |      GBP |