sql - Comparing tables information to retrieve from another -


i stuck on 1 problem. need create query in have table holds customerid , purchaseid number. in table have customerid , firstname , lastname of customer. need firstname , lastname of customers have recorded purchaseid of 1 or 2 or 7. when try code, customers second tabel (which holds firstname, lastname, , customerid) , not correct.

this code:

select firstname, lastname   customer, purchase  purchase.purchaseid = '1'     or purchase.purchaseid = '2'      or purchase.purchaseid = '7'  group firstname, lastname; 

i new sql , appreciate here.

select distinct c.firstname, c.lastname customer c join purchase p on p.customerid = c.customerid p.purchaseid in ('1', '2', '7') order  c.lastname, c.firstname 

update: in response @david aldridge comments, tested both forms (his , mine) on sql server 2008 r2 latest service pack. , generate identical cost execution plans. , in fact join form lower number of logical reads (but may vary actual id's choosen, of course)

i ran these 2 queries against sql server sample database, adventureworksdw2008 (since david mentioned "i've worked on data warehouses"):

select distinct c.firstname, c.lastname dbo.factinternetsales s  join dbo.dimcustomer c on c.customerkey = s.customerkey  s.productkey in (328, 333, 472)  select firstname,        lastname   dbo.dimcustomer c  exists (        select null          dbo.factinternetsales s         s.customerkey = c.customerkey ,               s.productkey in (328, 333, 472)) 

Comments