• ScottPletcher (8/1/2013)


    Luis Cazares (8/1/2013)


    You could find this article useful

    http://www.sqlservercentral.com/articles/T-SQL/88244/

    SELECT AttribID

    FROM MyTable

    WHERE FormatID IN (12,15)

    GROUP BY AttribID

    HAVING COUNT(DISTINCT FormatID ) = 2

    EXCEPT

    SELECT AttribID

    FROM MyTable

    WHERE FormatID <> 27

    The article's wrong, particularly this statement:

    "In SQL Server 2000 and before, you needed to use a WHERE NOT EXISTS, WHERE NOT IN, or an OUTER JOIN with a NULL filter to do the exclusion."

    HAVING can handle the whole check in ANY version of SQL that supports CASE (which even SQL 6.5 supported).

    SELECT AttribID

    FROM dbo.MyTable

    WHERE

    FormatID IN (12,15,27) --list ALL values that need tested, included and excluded

    GROUP BY

    AttribID

    HAVING

    MAX(CASE WHEN FormatID = 12 THEN 1 ELSE 0 END) = 1 AND --must be found

    MAX(CASE WHEN FormatID = 15 THEN 1 ELSE 0 END) = 1 AND --must be found

    MAX(CASE WHEN FormatID = 27 THEN 1 ELSE 0 END) = 0 --must NOT be found

    This is discussed at length in the comments of that article. There are several other approaches to the same thing. Then Jeff does his million row tests against all the various methods. Might be worth digging through the comments to see the results and the various ways of accomplishing this.

    _______________________________________________________________

    Need help? Help us help you.

    Read the article at http://www.sqlservercentral.com/articles/Best+Practices/61537/ for best practices on asking questions.

    Need to split a string? Try Jeff Modens splitter http://www.sqlservercentral.com/articles/Tally+Table/72993/.

    Cross Tabs and Pivots, Part 1 – Converting Rows to Columns - http://www.sqlservercentral.com/articles/T-SQL/63681/
    Cross Tabs and Pivots, Part 2 - Dynamic Cross Tabs - http://www.sqlservercentral.com/articles/Crosstab/65048/
    Understanding and Using APPLY (Part 1) - http://www.sqlservercentral.com/articles/APPLY/69953/
    Understanding and Using APPLY (Part 2) - http://www.sqlservercentral.com/articles/APPLY/69954/