4

这是使用 MYSQL 我的问题如下。我有一个棒球数据库,在那个棒球数据库中有一个主表,其中列出了每个曾经打过球的球员。还有一个击球台,可以跟踪每个球员的击球数据。我创建了一个将这两者结合在一起的视图;因此masterplusbatting表。我现在想找到自棒球开始以来每十年中 HR 最高的击球手。这是我尝试过的。

    select f.yearID, truncate(f.yearid/10,0) as decade,f.nameFirst, f.nameLast, f.HR
    from (
    select yearID, max(HR) as HOMERS
    from masterplusbatting group by yearID
    )as x inner join masterplusbatting as f on f.yearID = x.yearId and f.HR = x.HOMERS
    group by decade

您可以看到我截断了 yearID 以获取187, 188, 189etc 而不是1897, 1885,. 然后我按十年分组,认为它会给我每十年最高的值,但它没有返回正确的值。例如,它给了我 Adrian Beltre 在 2004 年的 48 HR,但每个人都知道 Barry Bonds 在 2001 年达到了 73 HR。谁能给我一些建议?

4

2 回答 2

2
SELECT
  Lookup.DecadeID,
  Data.*
FROM
(
  SELECT
    truncate(yearid/10,0) as decadeID,
    MAX(HR) as Homers
  FROM
    masterplusbatting
  GROUP BY
    truncate(yearid/10,0)
)
  AS lookup
INNER JOIN
  masterplusbatting AS data
    ON  data.yearid >= lookup.decadeID * 10
    AND data.yearid <  lookup.decadeID * 10 + 10
    AND data.HR     =  lookup.homers

为 MySQL 编辑

于 2012-10-15T21:35:51.507 回答
0

您的查询似乎聚合了错误的东西。在某个地方,我希望看到一个基于玩家的分组。

select truncate(mpb.yearid/10, 0) as decade, mpb.nameFirst, mpb.nameLast, sum(mpb.HR) as HRs
from masterplusbatting mpb
group by truncate(mpb.yearid/10, 0), mpb.nameFirst, mpb.nameLast

这给出了每十年的本垒打总数。现在,你想要拥有最多的人。为此,我将使用row_number()函数和子查询:

select decade, nameFirst, nameLast, HRs
from (select decade, nameFirst, nameLast, HRs,
             row_number() over (partition by decade order by HRs desc) as seqnum
      from (select truncate(mpb.yearid/10, 0) as decade, mpb.nameFirst, mpb.nameLast, sum(mpb.HR) as HRs
            from masterplusbatting mpb
            group by truncate(mpb.yearid/10, 0), mpb.nameFirst, mpb.nameLast
           ) t
     ) t
where seqnum = 1
order by 1

在 MySQL 等数据库中,您需要使用第二个连接来执行此操作:

select t.*
from (select truncate(mpb.yearid/10, 0) as decade, mpb.nameFirst, mpb.nameLast, sum(mpb.HR) as HRs
      from masterplusbatting mpb
      group by truncate(mpb.yearid/10, 0), mpb.nameFirst, mpb.nameLast
     ) t join
     (select decade, max(HRs) as maxHRs
      from (select truncate(mpb.yearid/10, 0) as decade, mpb.nameFirst, mpb.nameLast, sum(mpb.HR) as HRs
            from masterplusbatting mpb
            group by truncate(mpb.yearid/10, 0), mpb.nameFirst, mpb.nameLast
           ) t
      group by decade
     ) tsum
     on t.decade = tsum.decade and t.HRs = tsum.maxHRs
order by decade
于 2012-10-15T21:23:28.357 回答