0

我有两张桌子。第一个是 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

但是我只想检索薪水最高的用户的一个名字,那我做错了什么?

4

5 回答 5

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;
于 2013-09-01T21:34:24.003 回答
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; 
于 2013-09-01T21:40:31.143 回答
1

SQL小提琴

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)

结果

| F_NAME | F_SALARY |
|--------|----------|
|  Jenny |     5000 |
于 2013-09-01T21:48:01.227 回答
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语法是否有区别,但如果有类似的想法

于 2013-09-01T21:34:02.987 回答
0

我不太确定我是否理解,但我认为你想要做的是order by salaryand select top 1

于 2013-09-01T21:34:03.840 回答