选择MAX()会导致错误消息

时间:2014-11-28 17:10:27

标签: sql sql-server tsql

我需要创建一个T-SQL查询,它将返回job_positions表中的最高薪水以及拥有它的人的姓名。

到目前为止,我的解决方案是:

SELECT 
    MAX(e.salary) AS [Max salary]
    , p.firstname + ' ' + p.lastname AS [THE LUCKY MAN]
FROM 
    persons p 
JOIN 
    job_positions e ON (p.id_person = e.id_person)

但这会产生错误:

  

Msg 8120,Level 16,State 1,Line 67
  列'persons.firstname'在选择列表中无效,因为它不包含在任何一个中   聚合函数或GROUP BY子句。

     

Msg 8120,Level 16,State 1,Line 67
  列'persons.lastname'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

然而,它似乎只是不言自明;问题可能出在MAX函数上。删除后,结果为全名 - 工资表。我想知道为什么它不能只提取最大行...

3 个答案:

答案 0 :(得分:4)

如果只有一名员工可以获得Max salary,请尝试此操作。

SELECT TOP 1 e.salary                       AS [Max salary],
             p.firstname + ' ' + p.lastname AS [THE LUCKY MAN]
FROM   persons p
       JOIN job_positions e
         ON ( p.id_person = e.id_person )
ORDER  BY e.salary DESC 

如果多个获得最高薪水,请使用Window FunctionDense_Rank查找所有姓名。

;WITH cte
     AS (SELECT Dense_rank()
                  OVER (
                    ORDER BY e.salary)         Rn,
                e.salary                       AS [Max salary],
                p.firstname + ' ' + p.lastname AS [THE LUCKY MAN]
         FROM   persons p
                JOIN job_positions e
                  ON ( p.id_person = e.id_person ))
SELECT *
FROM   cte
WHERE  Rn = 1 

OR

SELECT TOP 1 WITH TIES e.salary                       AS [Max salary],
             p.firstname + ' ' + p.lastname AS [THE LUCKY MAN]
FROM   persons p
       JOIN job_positions e
         ON ( p.id_person = e.id_person )
ORDER  BY e.salary DESC 

答案 1 :(得分:0)

试试这个:

SELECT MAX(e.salary) AS [Max salary],
p.firstname+' '+p.lastname AS [THE LUCKY MAN]
FROM persons p JOIN job_positions e ON (p.id_person = e.id_person)
GROUP BY p.firstname, p.lastname -- group by clause needed

答案 2 :(得分:0)

最后找到了一个并不完全丑陋的解决方案:

SELECT 
    MAX(e.salary) AS [Max salary]
    , p.firstname + ' ' + p.lastname AS [THE LUCKY MAN]
FROM 
    persons p 
JOIN 
    job_positions e ON (p.id_person=e.id_person)
WHERE
    e.salary=(SELECT max(e.salary) FROM e.job_positions)

但我仍然想知道为什么不能只使用带有“join”的select的“MAX”。