sql query with two tables having reference key

215 views Asked by At

I have two tables:

Discounts(disid primary key)

Cust(custid primary key, disid ref discount(disid))

Now I need a query to get custid having all disid(discount coupons) and the customer may contain the same disid more than once.

3

There are 3 answers

0
hol On
select custid, count(distinct disid) from cust
group by custid
having count(*) = (select count(*) from discounts)
0
Samson On
SELECT COUNT(DISTINCT D.disid) FROM CUST C 
INNER JOIN DISCOUNTS D ON D.disid=C.disid GROUP BY D.disid
0
John Woo On

try either of this solutions:

SELECT  a.custid, COUNT(a.disid) totalCoupon
FROM    cust a  
            INNER JOIN discounts b 
                ON b.disid = a.disid 
GROUP BY a.custid

or

SELECT  a.custid, COUNT(a.disid) totalCoupon
FROM    cust a  
            INNER JOIN discounts b 
                ON b.disid = a.disid 
GROUP BY a.custid
HAVING   COUNT(a.disid) > 1 -- customers having the same (but more than 1) 
                            -- CouponID will only be shown here