简体   繁体   English

联接两个相关表

[英]Join on two related tables

I have two tables: One for Invoices and other for their payments: 我有两个表格:一个用于发票,另一个用于付款:

tbl_Invoice tbl_发票

发票

tbl_payment tbl_payment

付款

The desire output is as below: 期望输出如下:

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

Where: 哪里:

PSUM is Sum of Payments. PSUM是付款PSUM

IPRICE is Sum of Total_price of that client. IPRICE是该客户的Total_price的总和。

Query I tried is: 我试过的查询是:

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

But it gives wrong output: 但是它给出了错误的输出:

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

Seems like you want this. 好像您要这样。 This gives the total sum of the amt and the total_price with no grouping. 这给出了无分组的amttotal_price总和。 Your version groups by the invoice_id which is the difference: 您的版本按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

See SQL Fiddle with Demo 参见带有演示的SQL Fiddle

Another way you could write this is using subqueries: 编写此内容的另一种方法是使用子查询:

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

See SQL Fiddle with Demo 参见带有演示的SQL Fiddle

Both produce the same result: 两者产生相同的结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM