我使用lahman sabermetrics数据库学习MySQL
我试图查看哪些投手在整个数据中拥有最高的总体运行次数。击球表包含Home Runs(HR)列,而fielding表包含Position列(POS)
我已尝试过以下
SELECT playerID, SUM(HR) AS HR_SUM_TOTAL
FROM batting
GROUP BY playerID
WHERE (SELECT POS
FROM fielding
WHERE POS = "P")
ORDER BY HR_SUM_TOTAL DESC
有什么办法可以用嵌套选择做到这一点,还是更容易将POS列添加到击球表然后运行查询?
提前致谢
答案 0 :(得分:0)
如果我正确理解你的问题,一种方法就是
SELECT b.playerID, SUM(b.HR) HR_SUM_TOTAL
FROM batting b JOIN
(
SELECT DISTINCT playerID
FROM fielding
WHERE POS = 'P'
) f ON b.playerID = f.playerID
GROUP BY b.playerID
ORDER BY HR_SUM_TOTAL DESC
或
SELECT playerID, SUM(HR) HR_SUM_TOTAL
FROM batting
WHERE playerID IN
(
SELECT DISTINCT playerID
FROM fielding
WHERE POS = 'P'
)
GROUP BY playerID
ORDER BY HR_SUM_TOTAL DESC