SQL COUNT条件是结果另一个表

时间:2017-01-24 21:38:48

标签: sql

我是SQL的新手,我在这种情况下遇到了困难。

表1包含玩家在团队中的信息。

Table1

playerID   | yearID
----------------------
Player1    | 2000
Player1    | 2001
Player2    | 2000

表2包含名人堂的选票信息。玩家可以多次参加。

playerID | BallotYear | Inducted
---------------------------------
Player1  |   2010     |    N
Player1  |   2011     |    N
Player2  |   2010     |    Y

我试图计算玩家在Table1上出现的次数,条件是他们从未根据Table2进行过导入。

Desired Result

playerID  |  Count on Table 1
---------------------------
Player1   |        2

我遇到的问题是Player1返回4而不是2.我已经研究了许多不同的函数,但我仍然得到相同的结果。这就是我想出来的。

select Table1.playerID, count(Table1.playerID)
from Table1
join Table2 on Table1.playerID = Table2.playerID
where Table2.inducted = 'N'
group by Table1.playerID;

2 个答案:

答案 0 :(得分:2)

如果我理解正确,您希望过滤掉'Y'字段中曾有inducted的玩家。如果是这样的话:

select t1.playerId, count(*)
from table1 t1
where not exists (select 1
                  from table2 t2
                  where t2.playerID = t1.playerID and t2.inducted = 'Y'
                 )
group by t1.playerId;

答案 1 :(得分:0)

您可以使用左连接来实现此目的,这也将增加查询性能

select t1.playerId, count(*)
from table1 t1 left join
(select distinct playerID
                          from table2 
                          where inducted = 'Y'
                         ) t2 on t1.playerID = t2.playerID
where t2.playerId is null
group by t1.playerId
相关问题