如何 select 具有其他列最大值的列,以及另一个 table 中列的所有对应行?
How to select a column with max value of other column, and all corresponding rows of column in another table?
两个给定的表:
问题:Select成本最高的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)
以下查询有效。
但请下次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
两个给定的表:
问题:Select成本最高的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)
以下查询有效。
但请下次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