给定两个表:
John Smith | 84
Jane Bloggs| 100
John Smith | 182
Mark Antor | 219
84 | Swimming | 17
84 | Tennis | 36
100| Squash | 40
100| Swimming | 17
182| Tennis | 36
219| Golf | 47
219| Swimming | 15
219| Squash | 40
问题:选择成本最高的活动以及注册该活动的学生姓名。
结果应该是:活动栏(高尔夫)和学生栏(马克安东尼)。 在这种情况下,只有一名学生注册,但如果有更多学生注册,我想考虑一个案例。
我尝试了各种解决方案,但似乎无法解决。
任何提示表示赞赏,谢谢。
编辑:我看到我被否决了,我不想展示我尝试过的内容,因为我认为它偏离了目标,但这里是其中的一些:
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)
以下查询有效。
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
学生 |活动 :--------- | :-------- 马克·安托 |高尔夫球
db<>小提琴这里