表结构如下
id dept salary
1 30 2000
2 20 5500
3 30 6700
4 30 8900
5 30 9900
6 10 1120
7 20 8900
8 10 2400
9 30 2600
10 10 2999
我需要输出有两列:
Id和Salary
Id应该是唯一的,薪水应该有最高薪水
答案 0 :(得分:0)
如果同一部门中的其他人没有更高的工资,请使用NOT EXISTS
返回epmloyee。
select * from table t1
where not exists (select 1 from table t2
where t2.dept = t1.dept
and t2.salary > t1.salary)
Core SQL-99,可以与Oracle和Sybase一起使用!
替代解决方案:
select * from table
where (dept, salary) = (select dept, max(salary)
from table
group by dept)
在Core SQL-2003之外使用以下功能:F641,“行和表构造函数”。 (不知道Sybase和Oracle在这里支持什么......)
答案 1 :(得分:0)
SELECT ID,Salary FROM TABLE_NAME WHERE SALARY =(SELECT MAX(SALARY) FROM TABLE_NAME)
答案 2 :(得分:0)
SELECT a.Id, a.Salary
FROM table a
WHERE a.Salary = (SELECT MAX(Salary) FROM table
WHERE Id = a.Id)
答案 3 :(得分:0)
select * from (select * from dep order by salary desc, dep, id) t
group by t.dep
答案 4 :(得分:0)
使用单次扫描:
WITH SALARIES AS (
SELECT 1 ID, 30 DEPT, 2000 SALARY FROM DUAL UNION ALL
SELECT 2 ID, 20 DEPT, 5500 SALARY FROM DUAL UNION ALL
SELECT 3 ID, 30 DEPT, 6700 SALARY FROM DUAL UNION ALL
SELECT 4 ID, 30 DEPT, 8900 SALARY FROM DUAL UNION ALL
SELECT 5 ID, 30 DEPT, 9900 SALARY FROM DUAL UNION ALL
SELECT 6 ID, 10 DEPT, 1120 SALARY FROM DUAL UNION ALL
SELECT 7 ID, 20 DEPT, 8900 SALARY FROM DUAL UNION ALL
SELECT 8 ID, 10 DEPT, 2400 SALARY FROM DUAL UNION ALL
SELECT 9 ID, 30 DEPT, 2600 SALARY FROM DUAL UNION ALL
SELECT 10 ID, 10 DEPT, 2999 SALARY FROM DUAL
)
SELECT
MAX(ID) KEEP (DENSE_RANK LAST ORDER BY SALARY) ID,
MAX(SALARY) SALARY
FROM
SALARIES
GROUP BY
DEPT;
答案 5 :(得分:0)
以下三个查询都有效:
select t.dept, t.salary
from
(select dept,max(salary) as m_sal from tempdb..test
group by dept)x, tempdb..test t
where x.dept = t.dept
and x.m_sal = t.salary
select dept, id, salary as m_sal
from tempdb..test t1
where salary = (select max(salary) from tempdb..test t2 where t2.dept = t1.dept)
select t1.dept,t1.salary from tempdb..test t1
inner join
(select dept,max(salary) as m_sal from tempdb..test
group by dept)x on
t1.salary=x.m_sal and
t1.dept=x.dept