• TheSQLGuru (9/6/2013)


    For features that are "difficult" and/or don't get much attention it could be never. MERGE anyone?!? 🙂

    I see MERGE in use every now and then.

    INTERSECT admittedly has some exotic feeling over it, but for this particular problem it seems like a good choice. Note that the JOIN query could serve from a DISTINCT, seems it appears that (product_id, brand_id) is not a key in the table.

    However, if we generalise the problem to "show me all products that is in all brands", and there can be any number of brands, none of the options in the original post fits the bill. That's a relational division, and that is when you need Peter Larsson to tell you the most efficient solutions.

    One way to write that query would be:

    SELECT product_id

    FROM tbl

    GROUP BY product_id

    HAVING COUNT(DISTINCT brand_id) = (SELECT COUNT(DISTINCT brand_id) FROM tbl)

    [font="Times New Roman"]Erland Sommarskog, SQL Server MVP, www.sommarskog.se[/font]