How to use a group by in a subquery

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Sarah Smith

    How to use a group by in a subquery

    I am trying to create a query that will return the athlete's id, their first and last name in one column, the number of games they have participated in, and the number of medals they have won.

    So far I have this code:
    Code:
    SELECT ATHLETE.Athlete_id AS ID, (ATHLETE.Athlete_lname+", "+ATHLETE.Athlete_fname) AS Name, COUNT(REPRESENTATIVE.Athlete_id) AS [# of Game], 
    (SELECT COUNT(MEDAL.Cont_id)
    FROM MEDAL, ATHLETE, CONTESTANT, REPRESENTATIVE
    WHERE MEDAL.Cont_id=CONTESTANT.Cont_id 
    And CONTESTANT.Rep_id=REPRESENTATIVE.Rep_id 
    And REPRESENTATIVE.Athlete_id=ATHLETE.Athlete_id
    GROUP BY ATHLETE.Athlete_id
    HAVING COUNT(MEDAL.Cont_id) > 0
    ORDER BY COUNT(MEDAL.Cont_id) DESC) AS [# of Medal]
    FROM REPRESENTATIVE, ATHLETE
    WHERE ATHLETE.Athlete_id=REPRESENTATIVE.Athlete_id
    GROUP BY ATHLETE.Athlete_id, ATHLETE.Athlete_lname, ATHLETE.Athlete_fname;
    It is doing what I want except the results from the subquery are not grouped. I want them to be grouped by the athlete, however, whenever I try it says that "at most only one record can be returned by this subquery".
    Any help would be greatly appreciated
Working...