SQL Server:来自{TABLE}的SELECT DISTINCT [COL1] WHERE [COL2] ='A'和[COL2]<> 'B'

时间:2013-09-13 07:08:34

标签: sql sql-server select distinct multiple-records

我必须找到一个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'

3 个答案:

答案 0 :(得分: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 

答案 1 :(得分: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'
)

答案 2 :(得分: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 )