0

我一直在寻找如何在我的 SQL 查询中应用逻辑来实现我的目标。在这一点上,我愿意接受任何建议。

我有两个表之间有一个内部连接。这两张表是所有 MLB 棒球运动员(过去和现在)的完整列表,以及所有名人堂球员的表。我正在寻找每行一名唯一球员的查询结果,如果他们在名人堂中,则有一列用 Y 或 N 填充。

表 1 - 玩家

ID
HallofFameID
NameFirst
NameLast

表 2 - 名人堂

HallofFameID
YearID
Votes
Inducted

每个球员在球员表中都有一个条目,但他们的球员 ID 可能会在名人堂表中输入多次。在我生成的带有内部连接的查询中,将提取如下所示的行......

Player ID  |   NameFirst  |  NameLast  |  YearID  |  Votes  |  Inducted

001........| Don.........| Sutton......| 1992.....| 100.....| N

001........| Don.........| Sutton......| 1993.....| 89......| N 

001........| Don.........| Sutton......| 1994.....| 100.....| N   

001........| Don.........| Sutton......| 1998.....| 341.....| Y

002........| Mickey......| Mantle......| 1974.....| 341.....| Y So forth...

I would like my resulting query to not display the rows from 1992-1997 where Don Sutton was not elected, but just display the 1998 year, and then move down to the Mickey Mantle row with a Y. Also there are other players who have not been elected, that have a N next to their names for multiple years of Hall eligibility that I need to display on the same query result.

我已经包含了我的工作 SQL 以供参考。我不是在寻找任何人来编写我的 SQL,而是用关键字或我可能遗漏的逻辑为我指明正确的方向。提前致谢

Select  DISTINCT
    Master.namefirst, 
    Master.nameLast, 
    Master.HofID,
    HallOfFame.inducted,
    HallOfFame.yearid
FROM 
    HallOfFame 
INNER JOIN 
    Master On HallOfFame.hofID = Master.hofID
Group by 
    Master.nameFirst,
    Master.nameLast,
    Master.PlayerID,
    Master.hofID,
    HallOfFame.inducted,
    HallOfFame.yearid*
4

1 回答 1

0

试试这个:

SELECT
  m.namefirst, 
  m.nameLast, 
  m.HallofFameID,
  h1.inducted,
  h1.yearid
FROM HallOfFame h1
INNER JOIN
(
   SELECT PlayerID, MAX(YearID) LatestYear
   FROM HallOfFame 
   GROUP BY PlayerID
) h2 ON h1.PlayerID = h2.PlayerID AND h1.YearID = h2.LatestYear
INNER JOIN players m On h1.PlayerId = m.Id;

SQL 小提琴演示

这会给你:

| NAMEFIRST | NAMELAST | HALLOFFAMEID | INDUCTED | YEARID |
-----------------------------------------------------------
|       Don |   Sutton |            1 |        Y |   1998 |
|    Mickey |   Mantle |            2 |        Y |   1974 |
于 2012-12-16T06:25:45.040 回答