5

我有一个表,我需要从中选择所有名字不是唯一的人,并且只有在具有相似名字的人中都具有不同的姓氏时才应该选择该集合。

例子:

FirstN    LastN
Bill      Clinton
Bill      Cosby
Bill      Maher
Elvis     Presley
Elvis     Presley
Largo     Winch

我想获得

FirstN    LastN
Bill      Clinton

或者

FirstN    LastN
Bill      Clinton
Bill      Cosby
Bill      Maher

我试过了,但它没有返回我想要的。

SELECT * FROM Ids
GROUP BY FirstN, LastN
HAVING (COUNT(FirstN)>1 AND COUNT(LastN)=1))

[在 Aleandre P. Lavasseur 发表评论后编辑了我的帖子]

4

4 回答 4

7
WITH duplicates AS (
  SELECT firstn --, COUNT(*), COUNT(DISTINCT lastn)
    FROM ids
    GROUP BY firstn
    HAVING COUNT(*) = COUNT(DISTINCT lastn)
       AND COUNT(*) > 1
)
SELECT a.firstn, a.lastn
  FROM ids a INNER JOIN duplicates b ON (a.firstn = b.firstn)
  ORDER BY a.firstn, a.lastn

如果mysql不支持WITH,则内部查询:

SELECT a.firstn, a.lastn
  FROM ids a
      ,(SELECT firstn --, COUNT(*), COUNT(DISTINCT lastn)
          FROM ids
          GROUP BY firstn
          HAVING COUNT(*) = COUNT(DISTINCT lastn)
             AND COUNT(*) > 1
        ) b
  WHERE a.firstn = b.firstn
  ORDER BY a.firstn, a.lastn
于 2012-06-21T01:15:43.333 回答
3

你能试试这个:

SELECT A.FirstN, B.LastN
FROM (
SELECT FirstN
FROM Ids
GROUP BY FirstN
HAVING (COUNT(FirstN)>1)
) AS A
INNER JOIN Ids B ON (A.FirstN = B.FirstN)
GROUP BY A.FirstN, B.LastN
HAVING COUNT(B.LastN)=1
于 2012-06-21T01:25:05.330 回答
0

你可能可以这样做...

SELECT FirstN + LastN as FullName, COUNT(*)
FROM Ids
GROUP BY FirstN + LastN
HAVING COUNT(*) > 1

一定要检查空值,因为这会使连接无效。

于 2012-06-21T01:48:11.223 回答
0

与答案 2 类似,但只在名称重复的地方先注册(您说要获得的第一个结果)

select T.FirstN, T.LastN from  (
      select FirstN, LastN  from Ids
    group by FirstN, LastN
      having count(1) = 1) T
group by FirstN
having count(1) > 1;
于 2012-06-21T03:12:40.587 回答