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