0

如果我有一个表设置如下:

╔══════╦══════╗
║  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')
4

1 回答 1

3

好的,如果表上还有其他列,则此查询很有用。子查询的作用是单独获取A仅具有唯一性的B. MAX(B) = MIN(B)是一样的COUNT(DISTINCT B) = 1。然后通过 column 将子查询的结果连接回表本身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

或者

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
于 2013-03-12T03:05:48.330 回答