Search code examples
sql-serverselectrelational-division

MSSQL Select with "vertical"-where


I don't really know how to explain except with "vertical where".

Imagine the following table:

TAGID|PRODUCTID|SHOP_ID
59   |3418-7   |38
61   |3418-7   |38
60   |4227-4   |38
61   |4227-4   |38

Now I want to return all product IDs, that have relation to the tag IDs: 59,61. In other words, values of product ID where rows exist for both tag IDs.

So I want to return 3418-7, but not 4227-4

How do I write this as simple as possible in a SQL statement?

This is the working statement I have so far, but I feel this could be done in a much smarter way:

SELECT 
  productid 
FROM shop_tag_relations 
WHERE 
  productid IN (select productid from shop_tag_relations WHERE tagid=59) 
AND 
  productid IN (select productid from shop_tag_relations WHERE tagid=61)
GROUP BY productid,shop_id

Solution

  • SELECT PRODUCTID
    FROM T
    WHERE TAGID IN (59,61)
    GROUP BY PRODUCTID
    HAVING COUNT(DISTINCT TAGID) = 2
    

    Or

    SELECT PRODUCTID
    FROM T
    WHERE TAGID = 59
    INTERSECT
    SELECT PRODUCTID
    FROM T
    WHERE TAGID = 61