tags:

views:

44

answers:

2

Hello,

I want the customerid who bought product X and Y and Z, from the following schema:

Sales(customerid, productName, rid);

I could do the intersection:

select customerid from sales where productName='X' 
INTERSECT 
select customerid from sales where productName='X' 
INTERSTECT
select customerid from sales where productName='Z'

Is this the best I could do?

+6  A: 

Not sure if this works in postrgesql, but try:

select customerid 
from sales 
where productName in ('X', 'Y', 'Z')
group by customerid
having count(distinct productName) = 3
RedFilter
yes, that worked. I didn't know about that use of in. How else could you write it (that in)?Do you need the having count clause?
simpatico
`IN` is like an `OR`: this: `where productName in ('X', 'Y', 'Z')` can also be written as `where (productName ='X' OR productName = 'Y' OR productName = 'Z')`.
FrustratedWithFormsDesigner
The having count(distinct... clause is what ensures that only customers that have bought all three products are returned. Without it, the query would return all customers that had bought any of the three products.
Mark Bannister
This is a valid alternative. I'm curious about which one performs better.
leonbloy
+2  A: 

You could also select from sales 3 times:

select s1.customerID
from sales s1, sales s2, sales s3
where s1.productName = 'X'
    and S2.productName = 'Y'
    and S3.productName = 'Z'
    and (S1.customerID = S2.customerID
         and s2.customerID = s3.customerID);

Or rewrite using proper join syntax (might not be 100% though...)

select s1.customerID
from sales s1
inner join sales S2
    on s1.customerId = S2.customerID
inner join sales S3
    on s2.customerID = S3.customerId
where s1.productName = 'X'
    and S2.productName = 'Y'
    and S3.productName = 'Z';
FrustratedWithFormsDesigner
what do you mean by (might not be 100% though...)?
simpatico
I didn't actually try it, and I haven't used postgresql for several years, so I wasn't 100% I got the syntax exactly right, but probably close enough you could fix it if it had errors.
FrustratedWithFormsDesigner