0

怎样才能拿到每个部门的前两名薪水?表看起来像:

-------------------------
name     dept      sal
-------------------------
name1    CSE       100000
name2    CSE       200000
name3    ECE       200000
name4    EEE       400000
name5    CSE       700000
name6    ECE       600000
4

6 回答 6

1

第一部

SELECT dept
FROM  `Table` 
WHERE dept = 'CSE'
ORDER BY sal DESC 
LIMIT 0 , 2

二部

SELECT dept
FROM  `Table` 
WHERE dept = 'ECE' 
ORDER BY sal DESC 
LIMIT 0 , 2

每个上述查询将向您显示每个部门的前两个结果。

更新 :

SELECT dept, sal
FROM  `tbl_practice` 
WHERE dept =  'CSE'
OR dept =  'ECE'
ORDER BY sal DESC 
LIMIT 0 , 4
于 2012-05-22T11:02:47.417 回答
0

试试这个查询

select * from (
 SELECT  DISTINCT dept
        FROM    tableName )a
join tableName b
on a.dept >=b.dept
and 
a.dept <=b.dept
and sal >=(
select sal from tableName 
  where a.dept=b.dept
  order by sal limit 1,1
)
于 2012-05-22T12:36:02.877 回答
0
 select profession as d,(select max(sal) 
 from emp where profession like d) as firstsal,(
 select sal from emp 
 where profession like d order by sal desc limit 1,1) as secondsal from emp 
 GROUP BY profession
于 2012-09-20T09:29:02.243 回答
0

您需要使用聚合函数SUMGROUP BY子句。

SELECT dept, SUM(Sal) TotalSalary
FROM tableName
GROUP BY dept
Order By TotalSalary DESC
Limit 2
于 2012-05-22T10:53:01.303 回答
0

LIMIT在你的 statememt 中使用: http ://dev.mysql.com/doc/refman/5.5/en/select.html

于 2012-05-22T10:53:23.887 回答
0

不要以为在单个 SQL 语句中就可以获取数据。如果您想使用 SQL 来实现它,您将需要使用一个存储过程,该过程将遍历所有部门并使用 limit 和 order by 获取前 2 个薪水行。

于 2012-05-22T10:58:51.210 回答