2016-08-16 25 views
-2

这里是我的表:SQL:与不同的地方计数?

Players_Games_Table

MDATE PLAYER TEAM 
12  evra liverpool 
12  giggs liverpool 
12  smith liverpool 
13  evra leeds 
13  giggs liverpool 
13  smith manu 
14  evra spurs 
14  giggs liverpool 
14  smith chelsea 

我想返回的球员谁打了“利物浦”和至少一个其他球队球员的名字(PLAYER)。

事情是这样的:

select distinct player, count(team) from stats 
where team = 'liverpool' 
group by player 
having count(team) > 1; 
+1

_WHERE_之前_GROUP BY_ –

+0

双引号用于分隔标识符(例如,具有奇数名称的列)。对于字符串文字使用单引号。 – jarlh

+0

不需要做SELECT DISTINCT,你的GROUP BY返回没有重复。 – jarlh

回答

0

可以通过多种方式来实现,例如,你可以有一个相关子查询执行团队票:

select * 
from 
(
    select player, (select count(distinct team) from stats s2 
        where s2.player = s1.player) as teamcount 
    from stats s1 
    where team = 'Liverpool' 
) dt 
where teamcount > 1 

或者,标准GROUP BY ,与EXISTS

select player, count(distinct team) 
from stats s1 
where exists (select * from stats s2 
       where s1.player = s2.player 
       and s2.team = 'Liverpool') 
group by player 
having count(distinct team) > 1 
0
select a.PLAYER,count(*)+1 
from stats a 
join stats b 
on (a.PLAYER=b.PLAYER) 
where a.TEAM=liverpool and b.TEAM!=liverpool 
group by a.PLAYER;