如何选择多行分别在两列中具有相同值的位置?

时间:2015-06-01 14:04:06

标签: sql

例如,从下表中我想回到第2和第4小组,因为他们有多个同名的玩家。

--Team-- | --Player--
   1     |    John
   1     |    Billy
   2     |    Dillan
   2     |    Brady
   2     |    Brady
   3     |    John
   4     |    Gary
   4     |    Gary

2 个答案:

答案 0 :(得分:2)

如果您只想要团队名称(而不是重复玩家的名字),那么一种方法是使用SELECT DISTINCTGROUP BY

SELECT DISTINCT Team
FROM TeamPlayer
GROUP BY Team, Player
HAVING COUNT(*) > 1;

我提到,因为聚合查询中的SELECT DISTINCT几乎总是错误的,但这是一个有效的用法。

那就是说,我可能会更倾向于这样做:

SELECT Team
FROM TeamPlayer
GROUP BY Team
HAVING COUNT(*) > COUNT(DISTINCT Player);

答案 1 :(得分:0)

使用SELECT Team, Player FROM dbo.TeamPlayer GROUP BY Team, Player HAVING COUNT(*) > 1 + {{1}}:

{{1}}

here