[英]How to select a column with max value of other column, and all corresponding rows of column in another table?
Two given tables:两个给定的表:
Question: Select the activity with the highest cost and the names of the students that are registered in it.问题:Select 费用最高的活动以及其中注册的学生姓名。
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)
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高尔夫球
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.