假设我有一个带有两列的SQL表“Celebrities”:“fname”和“lname”:
fname | lname
---------+-------
Bill | Clinton
Bill | Gates
George | Bush
George | Clinton
Barack | Obama
我想编写一个查询,该查询返回表中每个人的名字和姓氏,其姓氏在“lname”列中至少出现两次。我该如何编写这个SQL查询?
答案 0 :(得分:59)
SELECT fname, lname FROM Celebrities
WHERE lname IN
(SELECT lname FROM Celebrities
GROUP BY lname HAVING COUNT (lname) >1)
答案 1 :(得分:9)
SELECT a.*
FROM CELEBRITIES a
JOIN (SELECT c.lname
FROM CELEBRITIES c
GROUP BY c.lname
HAVING COUNT(*) >= 2) b ON b.lname = a.lname
SELECT a.*
FROM CELEBRITIES a
WHERE EXISTS (SELECT NULL
FROM CELEBRITIES c
WHERE c.lname = a.lname
GROUP BY c.lname
HAVING COUNT(*) >= 2)
答案 2 :(得分:3)
select fname, lname
from
(
select fname, lname, count(*) over(partition by lname) as lcount
from Celebrities
) as S
where lcount > 1
在SQL Server 2008中测试。可能在支持count(*) over(...)