我有一张桌子,上面有player_id,team_id
我想找到所有在3个或以上球队中踢过的所有球员。
预期输出为:
玩家1,玩家2,队伍数
到目前为止,我有类似的东西
SELECT player_id as player1, player_id as player2, count(team_id) as number_of_teams
FROM player_history
WHERE ....
样本数据:
player_id | team_id
--------------------
001 | 23
001 | 15
001 | 21
002 | 23
002 | 21
002 | 15
002 | 34
003 | 23
003 | 15
003 | 34
003 | 21
004 | 12
004 | 11
004 | 23
应返回:
player1 | player2 | number_of_teams
-----------------------------------
001 | 002 | 3
001 | 003 | 3
002 | 003 | 4
答案 0 :(得分:1)
您应该做的是将自己加入表格,加入同一支球队,但使用不同的球员,一旦找到,就应该将结果表格分组并计数
自从我假设以来,每支球队中有超过2名球员,并且您隐含地在同一年中寻找不同的球员(在您的问题中未明确指定),我可以自由地将其添加到加入条件中 您当然可以将其删除
SELECT
p1,
p2,
COUNT(team_id) as total
FROM
(
SELECT
h1.team_id,
h1.player_id as p1,
h2.player_id as p2
FROM
player_history h1
INNER JOIN player_history h2 ON h1.team_id = h2.team_id AND h1.player_id != h2.player_id AND h1.year = h2.year
GROUP BY
h1.team_id,
h1.player_id
) sameteam
GROUP BY
p1,
p2
HAVING
total >= 3
请注意,示例结果不适合示例数据。第4场不应该在列表中
SQLFiddle here 希望对您有帮助