1

我必须找到一个SELECT DISTINCT [COL1] from {TABLE}可以从 [COL1] 中找到的所有内容,在 [COL2] 中有“A”,但在 [COL2] 中没有“B”在这种情况下,结果应该是“3”和“4”

桌子

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

3 回答 3

4
SELECT [COL1] from {TABLE} WHERE [COL2] = 'A' 
EXCEPT
SELECT [COL1] from {TABLE} WHERE [COL2] = 'B'

或者

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 
于 2013-09-13T07:11:40.713 回答
2
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'
)
于 2013-09-13T07:11:54.453 回答
1
;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 )
于 2013-09-13T07:12:14.357 回答