Helder Pinto
Helder Pinto

Reputation: 5

Join SQL results in one table

I need an SQL query that merge some results, but they have to match...

For example, see this image : Image of the tables

How can I do this? Is it possible?

Thanks!

Upvotes: 0

Views: 46

Answers (3)

Nguyễn Hải Triều
Nguyễn Hải Triều

Reputation: 1464

You can use left join, like this:

SELECT t1.product, t1.quantity, t1.avgprice, ISNULL(t2.buyprice, 0)
FROM table1 t1
   LEFT JOIN table2 t2
      ON t1.product = t2.product

Upvotes: 0

jarlh
jarlh

Reputation: 44776

select t1.product, t1.quantity, t1.avgprice, coalesce(t2.buyprice, 0)
from table1 t1
left join table2 t2 on t1.product = t2.product

The LEFT JOIN is there to also return table1 rows without a matching table2 row.

coalesce(t2.buyprice, 0) is used to return 0 if no t2.buyprice (i.e. t2.buyprice is null).

Upvotes: 2

Darek.K
Darek.K

Reputation: 128

You just need to use a query with JOIN statement.

SELECT t1.Product, t1.Quantity, t1.AVGPrice, t2.BuyPrice
FROM Table1 t1 
LEFT JOIN Table2 t2 ON t1.Product = t2.Product

Upvotes: 0

Related Questions