根据另一列ID选择列的最大值

时间:2016-10-18 19:18:29

标签: mysql sql

我试图在一个包含属性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

1 个答案:

答案 0 :(得分:1)

首先你按年获得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