得到所有共同的行

时间:2017-05-05 18:49:07

标签: sql oracle

我有一个玩家及其游戏的数据库。我试图获得一系列游戏,一组给定的玩家有共同点。

示例数据:

PLAYER  GAME
1       A
1       B
1       C
2       B
2       C
3       B
4       A
4       B
5       C
5       B

所以,给定:1, 2, 3, 4它会给我

GAME
B

并给出:1, 2, 5它会给我

GAME
B
C

3 个答案:

答案 0 :(得分:1)

一种方法是:

with cte as (
    select PLAYER, GAME from your_table where  player in (1, 2, 3, 4)
)
select GAME from cte
group by GAME
having count(distinct PLAYER) = (select count(distinct PLAYER) from cte)

答案 1 :(得分:0)

您可以使用条件聚合:

1,2,3,4:

select game
from your_table
group by game
having count(distinct case when player in (1, 2, 3, 4) then player end) = 4;

1,2,5:

select game
from your_table
group by game
having count(distinct case when player in (1, 2, 5) then player end) = 3;

Demo on rextester

答案 2 :(得分:0)

只是一个简单的WHERE子句:

SELECT DISTINCT game
FROM table_name
WHERE player in (1, 2, 3, 4);

SELECT DISTINCT game
FROM table_name
WHERE player in (1, 2, 5);

编辑:根据Gurwinder Singh的评论,将DISTINCT关键字添加到查询中。

相关问题