Search code examples
mysqljoinmax

How to select a column with max value of other column, and all corresponding rows of column in another table?


Two given tables:

Student | ID


 John Smith | 84
 Jane Bloggs| 100
 John Smith | 182
 Mark Antor | 219

ID | Activity | Cost


84 | Swimming | 17
84 | Tennis   | 36
100| Squash   | 40
100| Swimming | 17
182| Tennis   | 36
219| Golf     | 47
219| Swimming | 15
219| Squash   | 40

Question: Select the activity with the highest cost and the names of the students that are registered in it.

Result should be: activity column(golf) and students column(mark antony). In this case there's just one student registered but I want to account for a case if there are more students registered.

I tried all kinds of solutions but I cant seem to get it right.

Any tips appreciated, thanks.

edit: I see Im getting downvoted, I didnt want to show what I tried because I think its way off the mark but here is some of it:

SELECT s.Student, a.Activity from Activities as a inner join Students as s 
ON a.ID = s.ID where a.Cost = (select max(a.Cost))

SELECT s.Student, a.cost, a.Activity from Activities as a inner join Students `as s ON a.ID = s.ID`
group by s.Student having a.cost = max(a.cost)

Solution

  • Following query works.

    But please next time don't use images and you should also take a look at normalisation

    CREATE TABLE activity (
      `ID` INTEGER,
      `Activity` VARCHAR(8),
      `Cost` INTEGER
    );
    
    INSERT INTO activity
      (`ID`, `Activity`, `Cost`)
    VALUES
      ('84', 'Swimming', '17'),
      ('84', 'Tennis', '36'),
      ('100', 'Squash', '40'),
      ('100', 'Swimming', '17'),
      ('182', 'Tennis', '36'),
      ('219', 'Golf', '47'),
      ('219', 'Swimming', '15'),
      ('219', 'Squash', '40');
    
    CREATE TABLE students (
      `Student` VARCHAR(11),
      `ID` INTEGER
    );
    
    INSERT INTO students
      (`Student`, `ID`)
    VALUES
      ('John Smith', '84'),
      ('Jane Bloggs', '100'),
      ('John Smith', '182'),
      ('Mark Antor', '219');
    
    SELECT Student,Activity
    FROM  students s INNER JOIN (
    SELECT id,Activity FROm activity WHERE Cost = (SELECT MAX(Cost) FROM activity)) a ON s.ID = a.id
    
    Student    | Activity
    :--------- | :-------
    Mark Antor | Golf    
    

    db<>fiddle here