简体   繁体   中英

How can I fix this MySQL query?

I want to answer this question: In each year from 1962-2015, which New York Met hit the most home runs. In my results, I want to see the player's name, number of homers hit, and year. But in my results, I am getting the wrong player's name.

Here are the results I am getting:

1962 andercr01 34 1963 andercr01 17 1964 altmage01 20 1965 bearnla01 19 And so on.

Here is my query:

SELECT yearID, playerID, MAX(HR) as maxHR
FROM Batting
WHERE teamID='NYN'
GROUP BY yearID;

How can I fix this?

Use this:

SELECT yearID, playerName, MAX(HR) as maxHR
FROM Batting
WHERE teamID='NYN'
GROUP BY yearID;

You're not selecting the players name in your original query.

You need a join :

SELECT b.*
FROM Batting b JOIN
     (SELECT yearID, teamID, MAX(HR) as maxHR
      FROM Batting
      WHERE teamID = 'NYN'
      GROUP BY yearID, teamId
     ) bb
     ON bb.yearId = b.yearId and bb.teamId = b.teamId and bb.maxHR = b.HR;

Note: this will give duplicates in years where two players have the same maximum number of HR .

Also, I would expect the abbreviation for the New York Mets to be "NYM", not "NYN".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM