提问者:小点点

如何选择另一列的最大值的列,以及另一个表中该列的所有相应行?


两个给定的表:

问题:选择费用最高的activity和在其中注册的学生姓名。

结果应该是:activity栏(高尔夫)和学生栏(马克安东尼)。 在这种情况下,只有一个学生注册,但如果有更多的学生注册,我想说明一个案例。

我试过各种解决办法,但似乎都做不对。

谢谢你的建议。

编辑:我看到我被否决了,我不想展示我尝试了什么,因为我认为它离题了,但这里有一些:

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)

共1个答案

匿名用户

以下查询有效。

但请下次不要使用图像,你也应该看看标准化

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<;>此处小提琴