left join two tables on a non-unique column in right table

iman picture iman · Jul 16, 2016 · Viewed 11.4k times · Source

I have two tables in sql server and i wanna select and join some data from these table.the first tables have some customer like:

---------------
customer   id   
Dave       1    
Tom        2     
---------------

and second table i table of purchases that includes list of last purchases with cost and which customer bought that Product:

------------------
product    date       customer id
PC         1-1-2000   1
phone      2-3-2000   2
laptop     3-1-2000   1
------------------

i wanna select first table (customers info) with last date of their purchases! i tried left join but that doesn't give me last purchases becuase customer id is not unique in second table! how can i do this function with SQL server query? Regards

Answer

Gordon Linoff picture Gordon Linoff · Jul 17, 2016

If you just want the max date, use aggregation. I would recommend a left join for customers who have made no purchases:

select c.customer, c.id, max(p.date)
from customers c left join
     purchases p
     on c.id = p.customer_id
group by c.customer, c.id;