문제

I am trying to return the country, golfer name, golfer age, and average drive for the golfers with the highest average drive from each country.

However I am getting a result set with duplicates of the same country. What am I doing wrong? here is my code:

select distinct country, name, age, avgdrive
from pga.golfers S1
inner join
(select max(avgdrive) as MaxDrive
from pga.golfers
group by country) S2
on S1.avgdrive = s2.MaxDrive
order by avgdrive;

These are some of the results I've been getting back, I should only be getting 15 rows, but instead I'm getting 20:

COUN NAME                                  AGE   AVGDRIVE
---- ------------------------------ ---------- ----------
Can  Mike Weir                              35      279.9
T&T  Stephen Ames                           41      285.8
USA  Tim Petrovic                           39      285.8
Ger  Bernhard Langer                        47      289.3
Swe  Fredrik Jacobson                       30        290
Jpn  Ryuji Imada                            28        290
Kor  K.J. Choi                              37      290.4
Eng  Greg Owen                              33      291.8
Ire  Padraig Harrington                     33      291.8
USA  Scott McCarron                         40      291.8
Eng  Justin Rose                            25      293.1
Ind  Arjun Atwal                            32      293.7
USA  John Rollins                           30      293.7
NIr  Darren Clarke                          37        294
Swe  Daniel Chopra                          31      297.2
Aus  Adam Scott                             25      300.6
Fij  Vijay Singh                            42      300.7
Spn  Sergio Garcia                          25      301.9
SAf  Ernie Els                              35      302.9
USA  Tiger Woods                            29      315.2
도움이 되었습니까?

해결책

You are missing a join condition:

select s1.country, s1.name, s1.age, s1.avgdrive
from pga.golfers S1 inner join
     (select country, max(avgdrive) as MaxDrive
      from pga.golfers
      group by country
     ) S2
     on S1.avgdrive = s2.MaxDrive and s1.country = s2.country
order by s1.avgdrive;

Your problem is that some people in one country have the same average as the best in another country.

다른 팁

DISTINCT eliminated duplicate rows, not values in some fields. To get a list of countries with ages, names, and max drives, you would need to group the whole select by country.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top