SQL - 当日期不包含播放器时,仅选择播放器和日期

时间:2014-07-13 05:07:27

标签: sql

select player,date from nba.player_stats where tm='NOP';

这将返回新奥尔良鹈鹕队的一系列NBA球员以及球员参加比赛的一系列日期。每个日期都有多名球员。当玩家受伤并且不玩时,玩家不会出现在该特定日期的玩家列中。

我试图写一个查询,我可以说像WHERE player =' Ryan Anderson'如果不存在,请返回这些日期以及在这些日期播放的玩家列表。任何帮助将不胜感激。

抱歉,我在格式化表格时遇到了问题。它列出如此,除了包括更多日期:

**Player------------Date**

Ryan Anderson   2014-01-01

Jrue Holiday    2014-01-01

Anthony Davis   2014-01-01

Tyreke Evans    2014-01-01

Anthony Morrow  2014-01-01

Eric Gordon 2014-01-01

Brian Roberts   2014-01-01

Jeff Withey 2014-01-01

Darius Miller   2014-01-01

Al-Farouq Aminu 2014-01-01

Austin Rivers   2014-01-01

Alexis Ajinca   2014-01-01

Greg Stiemsma   2014-01-01

Alexis Ajinca   2014-01-04

Eric Gordon 2014-01-04

Jrue Holiday    2014-01-04

Tyreke Evans    2014-01-04

Al-Farouq Aminu 2014-01-04

Anthony Davis   2014-01-04

Brian Roberts   2014-01-04

Jeff Withey 2014-01-04

Greg Stiemsma   2014-01-04

Darius Miller   2014-01-04

3 个答案:

答案 0 :(得分:2)

这将显示Ryan Anderson没有参加比赛的所有球员

select player, date 
from nba.player_stats
where date not in (select date 
  from nba.player_stats 
  where player = 'Ryan Anderson')

答案 1 :(得分:2)

有很多方法可以编写查询,这里有一些例子(所有选择在Ryan Anderson没有时播放的NOP玩家);

使用NOT IN,只需检查他玩的日期并排除它们;

SELECT player, date
FROM player_stats
WHERE tm = 'NOP'
 AND date NOT IN (
   SELECT date FROM player_stats WHERE player='Ryan Anderson'
 );

使用NOT EXISTS,排除那些玩家日期相同且名称为“Ryan Anderson”的行;

SELECT player, date
FROM player_stats
WHERE tm = 'NOP'
 AND NOT EXISTS (
   SELECT 1 FROM player_stats ps
   WHERE player='Ryan Anderson' AND player_stats.date = ps.date
 );

使用LEFT JOIN,尝试与名为'Ryan Anderson'的玩家匹配并在同一日期,如果没有匹配则显示;

SELECT ps.player, ps.date
FROM player_stats ps
LEFT JOIN player_stats ps2
  ON ps2.player='Ryan Anderson' AND ps.date = ps2.date
WHERE ps.tm = 'NOP' AND ps2.player IS NULL

A simple SQLfiddle to test all of them

答案 2 :(得分:0)

我认为下面将会有所作为,尝试一下是否有效:

select player,date from nba.player_stats
where date not in (select date from nba.player_status where player='Ryan Anderson') order by date desc;