我正在尝试在具有属性teamID,salary,yearID的表中获取每年的最高薪水。不应该很难吗?这是我的查询:
SELECT teamID, MAX(tS.teamSalary), yearID
FROM
(SELECT
teamID,
sum(salary) AS teamSalary,
yearID
FROM salaries
GROUP BY teamID, yearID) tS
GROUP BY yearID;
内部查询工作正常,但外部查询仅报告每个组的第一个teamID。我究竟做错了什么?
Inner query output:
A 1 2000
B 1 2000
C 2 2000
A 2 2001
B 3 2001
A 2 2002
B 2 2002
Full query output:
A 1 2000
A 2 2001
A 2 2002
Desired output:
C 2 2000
B 3 2001
A 2 2002
最佳答案
首先,您会按年份获得maxSalary,然后您将获得更多信息:
SELECT teamID, salary, yearID
FROM salaries
JOIN
(SELECT MAX(salary) AS maxSalary,
yearID
FROM salaries
GROUP BY yearID) tS
ON ts.yearID = salaries.yearID
AND ts.maxSalary = salaries.salary
编辑:不确定是否要某年的最高薪水,然后它属于哪个团队,或者是否要按球队和年份的最高薪水。第二个选项在这里:
SELECT MAX(salary) AS maxSalary, yearID, teamID
FROM salaries
GROUP BY yearID, teamID
关于mysql - 根据另一个列ID选择一个列的最大值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40116318/