我不太确定如何将它标题为一个非常奇怪的问题。我正在构建一个稍微高级的查询,除了它返回该ID下的所有信息
之外它一切正常以下是我的代码:
select surname, salary_per_year, position _held, grade, name
from person inner join career_history on person.person_id = career_history.person_id
join grade on grade.person_id = career_history.person_id
join school on grade.school_id = school.school_id
where salary_per_year > 20000 and grade >65;
这会创建此表。
+----------+-----------------+--------------------+-------+---------------------------+
| surname | salary_per_year | position_held | grade | name |
+----------+-----------------+--------------------+-------+---------------------------+
| webster | 32000 | data analyst | 78 | Oxford University |
| webster | 23000 | data analyst | 78 | Oxford University |
| molina | 21000 | receptionist | 81 | UNAM |
| jones | 22000 | law assistant | 69 | University of Queensland |
| jones | 39000 | junior lawyer | 69 | University of Queensland |
| lovely | 26000 | junior analyst | 71 | Univesity of Bristol |
| clark | 23000 | junior banker | 68 | Harvard Univeristy |
| clark | 65000 | head banker | 68 | Harvard Univeristy |
| roberts | 26000 | researcher | 69 | MIT |
| roberts | 32000 | teacher | 69 | MIT |
| knght | 28000 | head of department | 92 | University of Barcelona |
| knght | 39000 | campus director | 92 | University of Barcelona |
| yanagowa | 39000 | database manager | 86 | Oxford Brookes Univeristy |
| yanagowa | 55000 | head of data | 86 | Oxford Brookes Univeristy |
+----------+-----------------+--------------------+-------+---------------------------+
我的问题是如何让它只显示每个姓氏的最高工资。 e.g
yanagowa 55000数据主管86牛津布鲁克斯大学 不是Yanagowa 39000数据库maanger 86牛顿布鲁克斯大学
请有人指出我是正确的直接!
答案 0 :(得分:2)
试一试。
SELECT surname, max(salary_per_year) as maxSalary, position_held, grade, name
FROM person
INNER JOIN career_history on person.person_id = career_history.person_id
JOIN grade on grade.person_id = career_history.person_id
JOIN school on grade.school_id = school.school_id
WHERE salary_per_year > 20000 and grade > 65
GROUP BY surname
ORDER BY Max(salary_per_year) DESC;
编辑
ORDER BY
实际上可以缩短,我在发布后就指出了这一点。
ORDER BY maxSalary DESC;
答案 1 :(得分:0)
注意:所有选定的字段必须具有组功能(例如,max,min,sum,avg),如果你正在填写它们
Select surname, max(salary_per_year) from @yourtable
group by surname