SQL Query在几十年内返回最大值

时间:2012-10-15 21:12:46

标签: mysql sql

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

    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

您可以看到我截断了年份ID以获得187, 188, 189等而不是1897, 1885,。然后我按照十年进行分组,认为它会给我每十年最高的一次,但它并没有返回正确的值。例如,它在2004年给了我Adrian Beltre 48个人力资源,但是每个人都知道Barry Bonds在2001年达到了73个人力资源。有人可以给我一些指示吗?

2 个答案:

答案 0 :(得分: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编辑

答案 1 :(得分: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