SQL Server:从 {TABLE} 中选择不同的 [COL1],其中 [COL2] = 'A' 和 [COL2] <> 'B'



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

相关内容

  • 没有找到相关文章

最新更新