我有两张桌子。第一个是T_EMPLOYEE
create table t_employee
(
f_id number(8, 2) not null primary key,
f_name varchar(200),
);
第二个是T_SALARY
create table t_salary
(
f_id number(8, 2) not null primary key,
f_employee_id number(8,2),
f_salary number(8, 2)
);
ALTER TABLE t_salary ADD CONSTRAINT fk_salary
FOREIGN KEY (f_employee_id) REFERENCES t_employee;
我想获得最高工资和相应员工的姓名,我写了这个查询
select t_employee.f_name, MAX(f_salary)
from t_salary
inner join t_employee on t_salary.f_employee_id=t_employee.f_id
group by f_name;
但结果如下:
Jenny 5000
Andy 3000
Mary 1000
但是我想只检索一个薪水最高的用户名,那么我做错了什么?
答案 0 :(得分:1)
您可以使用rownum psuedcolumn
select
f_name,
f_salary
from (
select
t_employee.f_name,
MAX(f_salary) as f_salary
from
t_salary
inner join
t_employee
on t_salary.f_employee_id=t_employee.f_id
group by
f_name
order by
max(f_salary) desc
) x
where
rownum = 1;
答案 1 :(得分:1)
select f_name,
f_salary
from (
select t_employee.f_name,
t_salary.f_salary,
dense_rank() over (order by t_salary.f_salary desc) as rnk
from t_salary
inner join t_employee on t_salary.f_employee_id=t_employee.f_id
) t
where rnk = 1;
答案 2 :(得分:1)
Oracle 11g R2架构设置:
CREATE TABLE t_employee
("f_id" int, "f_name" varchar2(9))
;
INSERT ALL
INTO t_employee ("f_id", "f_name")
VALUES (1, 'Jenny')
INTO t_employee ("f_id", "f_name")
VALUES (2, 'Andy')
INTO t_employee ("f_id", "f_name")
VALUES (3, 'Mary')
SELECT * FROM dual
;
CREATE TABLE t_salary
("f_id" int, "f_employee_id" int, "f_salary" int)
;
INSERT ALL
INTO t_salary ("f_id", "f_employee_id", "f_salary")
VALUES (1, 1, 5000)
INTO t_salary ("f_id", "f_employee_id", "f_salary")
VALUES (2, 2, 3000)
INTO t_salary ("f_id", "f_employee_id", "f_salary")
VALUES (3, 3, 1000)
SELECT * FROM dual
;
查询1 :
select t_employee."f_name", "f_salary"
from t_salary
inner join t_employee on t_salary."f_employee_id"=t_employee."f_id"
where "f_salary" = (select max("f_salary") from t_salary)
<强> Results 强>:
| F_NAME | F_SALARY |
|--------|----------|
| Jenny | 5000 |
答案 3 :(得分:0)
试试这个
select t_employee.f_name, f_salary
from t_salary inner join t_employee on t_salary.f_employee_id=t_employee.f_id
where f_salary = (
select max(f_salary)
from t_salary
where rownum <= 1)
我不确定Oracle语法是否存在差异,但是如果有这样的想法
答案 4 :(得分:0)
我不太确定我理解,但我认为你要做的是order by salary
和select top 1
。