mysql 去重 rownumber_MYSQL-实现ORACLE 和SQLserver数据中- row_number() over(partition by ) 分组排序功能...

网上看见了好多例子都基本上是一样的,没有过多的解释,对于一个初学MySQL来说有点难,我把部分转摘过来如下 原文:http://www.cnblogs.com/buro79xxd/archive/2012/08/29/2662489.html

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

创建表格:2.来创建实例数据:

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);

数据效果图:

77b46e56ee877e6c001b728e07754cd4.png

实现 3. http://www.kaishixue.com/mysql/14.html 帖子中SQL的实现

SELECT

empid,

deptid,

salary,

rank

FROM

(

SELECT

heyf_tmp.empid,

heyf_tmp.deptid,

heyf_tmp.salary,

IF (

@pdept = heyf_tmp.deptid ,@rank :[email protected] + 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

@pdept := NULL ,@rank := 0

) a

) result;

对于这一段我是羞涩难懂的,虽然实现了需求的结果,看了很久才明白过来,现在我小修改一下 用存储过程实现

CREATE PROCEDURE testrank ()

BEGIN

SET @num = 0;

SET @pdept = NULL;

SELECT

result.empid,

result.deptid,

result.salary,

result.rank

FROM

(

SELECT

s.empid,

s.deptid,

s.salary,

IF (

@pdept = s.deptid ,@num :[email protected] + 1 ,@num := 1

) AS rank,

@pdept := s.deptid

FROM

heyf_t10 s

ORDER BY

s.deptid ASC,

s.salary DESC

) result;

END

执行 语句 call testrank();

结果图:

0fc38ed9e98e950cfe959930250527ba.png

另外一种思路是上文链接的作者的如下:

SELECT

h.`empid`,

h.`deptid`,

h.`salary`,

count(*) AS rank

FROM

heyf_t10 AS h

LEFT OUTER JOIN heyf_t10 AS r ON h.deptid = r.deptid

AND h.`salary` <= r.`salary`

GROUP BY

h.`empid`,

h.`deptid`,

h.`salary`

ORDER BY

h.deptid,

h.salary DESC;

他们谁好谁差不清楚 反正多了一个思路。这样就是好的。

时间: 06-19

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值