如何选择具有最大值的行?

时间:2016-04-25 17:38:08

标签: sql oracle

select NATIONALPLAYERS.FIRSTNAME||' '|| NATIONALPLAYERS.LASTNAME as PlayerName, NATIONALPLAYERS.EXPERIENCEID, experience

from NATIONALPLAYERS

INNER JOIN (select experienceid, MAX( experiences.nationalgames + experiences.internationalgames ) as experience

from experiences 

group by experiences.EXPERIENCEID)plexperience
 on plexperience.experienceid = NATIONALPLAYERS.experienceid;

这会显示PlayerNameExperienceIDExperience的所有记录,即使我只询问experience的最大值。

2 个答案:

答案 0 :(得分:0)

您按EXPERIENCEID分组并获得每个EXPERIENCE的最大值 - 您没有找到与EXPERIENCEID最大对应的EXPERIENCE

如果您想找到最大体验的值,那么您需要以下内容:

SELECT *
FROM   (
  select n.FIRSTNAME ||' '|| n.LASTNAME as PlayerName
         n.experienceid,
         e.nationalgames + e.internationgames as Experience
  from   NATIONALPLAYERS n
         INNER JOIN
         EXPERIENCE e
         ON ( e.experienceid = n.experienceid )
  ORDER BY Experience DESC
)
WHERE ROWNUM = 1;

或者,如果有多个最高行:

SELECT *
FROM   (
  select n.FIRSTNAME ||' '|| n.LASTNAME as PlayerName
         n.experienceid,
         e.nationalgames + e.internationgames as Experience,
         RANK() OVER ( ORDER BY e.nationalgames + e.internationgames DESC )
           AS rn
  from   NATIONALPLAYERS n
         INNER JOIN
         EXPERIENCE e
         ON ( e.experienceid = n.experienceid )
  ORDER BY Experience DESC
)
WHERE rn = 1;

答案 1 :(得分:0)

您缺少的是最大经验。您正在检查experience_id但不确保体验值是最大值

查询应该是:

SELECT 
    NATIONALPLAYERS.FIRSTNAME||' '|| NATIONALPLAYERS.LASTNAME as PlayerName, 
    NATIONALPLAYERS.EXPERIENCEID, 
    experience

from NATIONALPLAYERS
INNER JOIN (
    select 
        experienceid, 
        MAX( experiences.nationalgames +     experiences.internationalgames ) as experience

    from experiences 
    group by experiences.EXPERIENCEID) AS plexperience
 on 
    plexperience.experienceid = NATIONALPLAYERS.experienceid
    **plexperience.experience = NATIONALPLAYERS.experience;**