Vishal Suthar
Vishal Suthar

Reputation: 17183

Join on two related tables

I have two tables: One for Invoices and other for their payments:

tbl_Invoice

Invoice

tbl_payment

Payment

The desire output is as below:

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

Where:

PSUM is Sum of Payments.

IPRICE is Sum of Total_price of that client.

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

Upvotes: 0

Views: 68

Answers (1)

Taryn
Taryn

Reputation: 247610

Seems like you want this. This gives the total sum of the amt and the total_price with no grouping. Your version groups by the invoice_id which is the difference:

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

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

Both produce the same result:

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

Upvotes: 1

Related Questions