SQL选择重复的位置,但在另一列上不同

时间:2009-02-24 18:54:20

标签: sql tsql

我有下表:

uid | key | email
-----------------
1   |  1  | test@test.com
2   |  2  | test@test.com
3   |  3  | test@test.com
4   |  4  | test@test.com
5   |  4  | test@test.com
6   |  4  | test@test.com
7   |  6  | abce@test.com
8   |  7  | defg@test.com

我想抓住具有不同密钥但重复电子邮件值的所有行

结果应该如下:

uid | key | email
-----------------
1   |  1  | test@test.com
2   |  2  | test@test.com
3   |  3  | test@test.com

2 个答案:

答案 0 :(得分:2)

SELECT MIN(uid) as uid, key, email
FROM Keys k INNER JOIN 
    (SELECT email FROM KEYS GROUP by email HAVING COUNT(email) > 1 ) k2
    ON k.email = k2.email
GROUP BY key, email
HAVING COUNT(key) = 1

答案 1 :(得分:1)

SELECT * FROM table
WHERE email NOT IN
(
SELECT email 
FROM table GROUP BY email
HAVING COUNT(email) <= 1)
AND key IN
(
SELECT key
FROM table
GROUP BY key
HAVING COUNT(key) = 1 
)