2016-08-16 67 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;