SQL Server : SELECT DISTINCT [COL1] from {TABLE} WHERE [COL2] = 'A' AND [COL2] <> 'B'

886 views Asked by At

I have to find a SELECT DISTINCT [COL1] from {TABLE} there can find all from [COL1] there have 'A' in [COL2] but not 'B' in [COL2] In this case '3' and '4' should be the result

TABLE

   [COL1]      [COL2]
   ----        ----
   '1'          'A'
   '1'          'B'
   '1'          'C'
   '2'          'B'
   '2'          'C'
   '3'          'A'
   '3'          'C'
   '4'          'A'
   '4'          'D'
3

There are 3 answers

6
Martin Smith On BEST ANSWER
SELECT [COL1] from {TABLE} WHERE [COL2] = 'A' 
EXCEPT
SELECT [COL1] from {TABLE} WHERE [COL2] = 'B'

Or

SELECT [COL1]
FROM   {TABLE}
GROUP  BY [COL1]
HAVING MAX(CASE
             WHEN [COL2] = 'A' THEN 1
             ELSE 0
           END) = 1
       AND MAX(CASE
                 WHEN [COL2] = 'B' THEN 1
                 ELSE 0
               END) = 0 
0
lc. On
SELECT DISTINCT [COL1]
FROM {TABLE} t1
WHERE t2.[COL2] = 'A'
AND NOT EXISTS
(
    SELECT 1
    FROM {TABLE} t2
    WHERE t2.[COL1] = t1.[COL1]
    AND t2.[COL2] = 'B'
)
0
Giannis Paraskevopoulos On
;WITH MyCTE AS
(
    SELECT DISTINCT [COL1]
    FROM   [TABLE]
    WHERE  [COL2] = 'B'
)
SELECT DISTINCT [COL1]
FROM   [TABLE]
WHERE  [COL2] = 'A'
AND    [COL1] NOT IN (SELECT [COL1] FROM MyCTE )