如果我的表设置如下:
╔══════╦══════╗
║ A ║ B ║
╠══════╬══════╣
║ Sam ║ sec2 ║
║ Sam ║ sec2 ║
║ Sam ║ sec2 ║
║ Fred ║ sec1 ║
║ Fred ║ sec2 ║
║ Fred ║ sec1 ║
║ Joe ║ sec1 ║
║ Joe ║ sec1 ║
╚══════╩══════╝
我希望结果是
╔═════╦══════╗
║ A ║ B ║
╠═════╬══════╣
║ Sam ║ sec2 ║
║ Sam ║ sec2 ║
║ Sam ║ sec2 ║
║ Joe ║ sec1 ║
║ Joe ║ sec1 ║
╚═════╩══════╝
所以基本上我想查询sec1或sec2但不是两者的人,我想留下重复项。
我的尝试:
SELECT A, B
FROM TABLE
WHERE (A = 'SAM' OR A = 'FRED' OR A = 'JOE') AND NOT (B = 'sec1' AND B = 'sec2')
答案 0 :(得分:3)
好的,如果表上还有其他列,则此查询很有用。子查询的作用是单独获取仅A
唯一的B
。 MAX(B) = MIN(B)
与COUNT(DISTINCT B) = 1
相同。然后,通过列A
将子查询的结果连接回表本身。
SELECT y.*
FROM tableName y
INNER JOIN
(
SELECT A
FROM tableName
GROUP BY A
HAVING MAX(B) = MIN(B)
AND MAX(B) IN ('sec1', 'sec2')
) x ON y.A = x.A
OR
SELECT y.*
FROM tableName y
INNER JOIN
(
SELECT A
FROM tableName
GROUP BY A
HAVING COUNT(DISTINCT B) = 1
AND MAX(B) IN ('sec1', 'sec2')
) x ON y.A = x.A