2015-10-22 63 views
2

我在练习sql,并且遇到了这个问题。我不确定的SQL逻辑,更具体地说,它似乎是我完全错误使用组。SQL错误,组的错误执行

问题: 在同一年龄段的所有员工中打印薪金最高的员工的姓名和年龄。

employee(sid, sname, sex, age, year, salary) 

第一次尝试:

select E.sname, E.age 
from employee E 
where E.salary= max(E.salary) 
group by E.sname, E.age 

Error: Invalid SQL: ORA-00934: group function is not allowed here 

第二次尝试

select E.sname, E.age 
from employee E 
group by E.sname, E.age 
having E.salary= max(E.salary) 
Error: Invalid SQL: ORA-00979: not a GROUP BY expression 
+0

使用子选择来获得最高工资。 – jarlh

+0

@jarih你能解释我的实现有什么问题吗? – Sam

+0

@Sam它是无效的SQL - WHERE在分组之前执行,所以你不能有一个聚合,'HAVING'只适用于分组表达式或聚合。您必须使用其他方法(子选择,分区等)来获取每个组中具有最高值的记录。 –

回答

2

这可能工作:

select E.sname, E.age 
from employee E 
where E.salary= 
    (select max(salary) 
    from employee a 
    where a.age = E.age 
    ) 
0

到这个问题的一个简单的方法是使用解析函数rank

select sname, age, salary 
from (
select sname, age, salary, 
rank() over(partition by age order by salary desc) rnk 
from employee) t 
where rnk = 1 

或者纠正查询你有

select E.sname, E.age, E.salary 
from employee E 
where (age, salary) in (select age,max(salary) from employee group by age) 
0

注意,使用GROUP BY对那些不属于聚合函数中的字段,并且您不能在WHERE子句中使用聚合函数。

SELECT e1.name, e1.age 
    FROM employee e1, (SELECT age, MAX(salary) AS max_salary FROM employee GROUP BY age) e2 
WHERE e1.salary = e2.max_salary 
    AND e1.age = e2.age;