Reputation: 3
I have 2 Tables X & Y,
Table X(has 5 records)
Cust_Id Prod_Key
1 'A'
1 'D'
2 'C'
3 'D'
2 'B'
Table Y (has 2 records)
Prod_Key
'A'
'D'
Need SQL to list the Cust_ID which has all the products from Table Y. ~ Cannot hard code as the table keeps updated
Upvotes: 0
Views: 1153
Reputation: 5656
You can do the same thing using INNER JOIN
with GROUP BY
and COUNT
as below
SELECT x.Cust_Id
FROM X x
INNER JOIN Y y ON y.Prod_Key = x.Prod_Key
GROUP BY x.Cust_Id
HAVING COUNT(y.Prod_Key) = (SELECT COUNT(*) FROM Y)
Upvotes: 1
Reputation: 995
You can try the following code to get the unique list of Cust_IDs
select DISTINCT Cust_Id from X where x.Prod_key in (select y.Prod_key from Y)
Upvotes: 0
Reputation: 3770
You can also try inner join as you need only the customerid
whose productkey
is present in table y
SELECT x.Cust_Id
FROM x
INNER JOIN y
ON x.Prod_Key = y.Prod_key
Upvotes: 0
Reputation: 1423
You can try the following:
select
cust_id
from
Y
LEFT OUTER JOIN
X
on Y.Prod_key = X.Prod_key
Group by
Cust_id
having
count(DISTINCT X.Prod_key) = (select count(*) from Y);
Upvotes: 3