1

I have following Product table and ProductTag tables -

ID  | Product
-------------- 
1   | Product_A
2   | Product_B
3   | Product_C

TagID   |   ProductID
----------------------
1       |      2
1       |      3
2       |      1
2       |      2
2       |      3
3       |      1
3       |      2

Now I need a SQL query that return all products list which are having both Tag 1 and 2. Result should be as given below -

ProductID   |    Product   
------------------------
2           |      Product_B
3           |     Product_C

Please suggest how can i write a MS SQL query for this.

1 Answer 1

1
SELECT  p.ID, p.Product
FROM    Product p
        INNER JOIN ProductTag pt
            ON p.ID = pt.ProductID
WHERE   pt.TagID IN (1, 2)           -- <== Tags you want to find
GROUP   BY p.ID, o.Product
HAVING  COUNT(*) = 2                 -- <== tag count on WHERE clause

however, if TagID is not unique on every Product, you need to count only the distinct product.

HAVING  COUNT(DISTINCT pt.TagID) = 2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.