如何编写下表中的查询

时间:2013-10-04 07:29:53

标签: mysql

我的表名为emp:

表格数据如下:

   id    name dep_id salary
    1      x     10    2000
    2      y     20    3000
    3      z     30    1000
    4      c     40    500
    5      xc    50    100
    6      b     60    10
    7      l     70    4000
    8      m     80    5000
    9      n     90    10000
    10     dd    100   100
    11      gg    20    4000
    12      vv    10    2000

我的要求是向每个部门显示最高两位工资员工的详细信息。

2 个答案:

答案 0 :(得分:0)

这是一种方法,但我希望如果这是一个测试,他们不会相信你写的: -

SELECT id, name, dep_id, salary
FROM
(
    SELECT id, name, dep_id, salary, @DepCnt := IF(@Dep=dep_id, @DepCnt + 1, 1) AS DepartmentCounter, @Dep:=dep_id
    FROM
    (
        SELECT id, name, dep_id, salary
        FROM emp
        ORDER BY dep_id, salary DESC
    ) a
    CROSS JOIN (SELECT @DepCnt:=1, @Dep:=0) Sub1
) Sub2
WHERE DepartmentCounter <= 2

内部选择以deparatment顺序获取所有行,然后在该范围内降低工资。

然后下一个外部选择为每一行添加一个计数器,从1开始,每个部门的工资最高。

然后外部选择只会获得计数器为1或2的那些。

SQLfiddle的例子: -

http://sqlfiddle.com/#!2/3643e/1

编辑 - 如果超过1人拥有相同的薪水(前2名薪水之一),则扩展以恢复详细信息: -

SELECT id, name, dep_id, salary
FROM
(
    SELECT id, name, dep_id, salary, @DepCnt := IF(@Dep=dep_id, IF(@PrevSalary=salary, @DepCnt, @DepCnt + 1), 1) AS DepartmentCounter, @Dep:=dep_id, @PrevSalary:=salary
    FROM
    (
        SELECT id, name, dep_id, salary
        FROM emp
        ORDER BY dep_id, salary DESC
    ) a
    CROSS JOIN (SELECT @DepCnt:=1, @Dep:=0, @PrevSalary:=0) Sub1
) Sub2
WHERE DepartmentCounter <= 2

答案 1 :(得分:0)

<强>查询

select e.* 
from emp e
inner join (
              SELECT 
              dep_id,
              salary,
              ( 
                CASE dep_id 
                WHEN @curType 
                THEN @curRow := @curRow + 1 
                ELSE @curRow := 1
                AND @curType := dep_id END
                )AS sequence_No
                FROM emp, 
                (SELECT @curRow := 0, @curType := '') r
                ORDER BY  dep_id,salary desc 
)t on t.dep_id=e.dep_id and t.salary=e.salary
where t.sequence_No<=2

<强> Results

| ID | NAME | DEP_ID | SALARY |
|----|------|--------|--------|
| 13 |   xx |     10 |   5000 |
|  1 |    x |     10 |   2000 |
| 12 |   vv |     10 |   2000 |
| 11 |   gg |     20 |   4000 |
|  2 |    y |     20 |   3000 |
|  3 |    z |     30 |   1000 |
|  4 |    c |     40 |    500 |
|  5 |   xc |     50 |    100 |
|  6 |    b |     60 |     10 |
|  7 |    l |     70 |   4000 |
|  8 |    m |     80 |   5000 |
|  9 |    n |     90 |  10000 |
| 10 |   dd |    100 |    100 |