# mysql分两次组_求解释啊叫苦连天看不懂 mysql实现分组后组内排序

row_number() OVER (PARTITION BY COL1 ORDER BY COL2) 表示根据COL1分组，在分组内部根据 COL2排序，而此函数计算的

drop table if exists heyf_t10;

create table heyf_t10 (empid int ,deptid int ,salary decimal(10,2) );

insert into heyf_t10 values

(1,10,5500.00),

(2,10,4500.00),

(3,20,1900.00),

(4,20,4800.00),

(5,40,6500.00),

(6,40,14500.00),

(7,40,44500.00),

(8,50,6500.00),

(9,50,7500.00);

2. 确定需求: 根据部门来分组,显示各员工在部门里按薪水排名名次.

+-------+--------+----------+------+

| empid | deptid | salary | rank |

+-------+--------+----------+------+

| 1 | 10 | 5500.00 | 1 |

| 2 | 10 | 4500.00 | 2 |

| 4 | 20 | 4800.00 | 1 |

| 3 | 20 | 1900.00 | 2 |

| 7 | 40 | 44500.00 | 1 |

| 6 | 40 | 14500.00 | 2 |

| 5 | 40 | 6500.00 | 3 |

| 9 | 50 | 7500.00 | 1 |

| 8 | 50 | 6500.00 | 2 |

-----------------------------------------------

select empid,deptid,salary,rank from (

select heyf_tmp.empid,heyf_tmp.deptid,heyf_tmp.salary,@rownum:=@rownum+1 ,

if(@pdept=heyf_tmp.deptid,@rank:=@rank+1,@rank:=1) as rank,

@pdept:=heyf_tmp.deptid

from (

select empid,deptid,salary from heyf_t10 order by deptid asc ,salary desc

) heyf_tmp ,

(select @rownum :=0 , @pdept := null ,@rank:=0) a

) result ;

+-------+--------+----------+------+

| empid | deptid | salary | rank |

+-------+--------+----------+------+

| 1 | 10 | 5500.00 | 1 |

| 2 | 10 | 4500.00 | 2 |

| 4 | 20 | 4800.00 | 1 |

| 3 | 20 | 1900.00 | 2 |

| 7 | 40 | 44500.00 | 1 |

| 6 | 40 | 14500.00 | 2 |

| 5 | 40 | 6500.00 | 3 |

| 9 | 50 | 7500.00 | 1 |

| 8 | 50 | 6500.00 | 2 |

+-------+--------+----------+------+

9 rows in set (0.00 sec)

-------------------------------------------------------

select heyf_tmp.empid,heyf_tmp.deptid,heyf_tmp.salary,@rownum:=@rownum+1 ,

if(@pdept=heyf_tmp.deptid,@rank:=@rank+1,@rank:=1) as rank,

@pdept:=heyf_tmp.deptid

------解决方案--------------------

2楼说什么我没看懂

• 0
点赞
• 0
收藏
• 打赏
• 0
评论
09-06 235
02-07 1383
03-09 3365
08-06 1008
04-29 1957

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。