魂心

mysql 实现 sqlserver的row_number over() 方法

1.创建表

CREATE TABLE `heyf_t10` (
`empid` int(11) DEFAULT NULL,
`deptid` int(11) DEFAULT NULL,
`salary` decimal(10,2) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.添加数据

INSERT INTO `heyf_t10` VALUES (1, 10, 5500.00);
INSERT INTO `heyf_t10` VALUES (2, 10, 4500.00);
INSERT INTO `heyf_t10` VALUES (3, 20, 1900.00);
INSERT INTO `heyf_t10` VALUES (4, 20, 4800.00);
INSERT INTO `heyf_t10` VALUES (5, 40, 6500.00);
INSERT INTO `heyf_t10` VALUES (6, 40, 14500.00);
INSERT INTO `heyf_t10` VALUES (7, 40, 44500.00);
INSERT INTO `heyf_t10` VALUES (8, 50, 6500.00);
INSERT INTO `heyf_t10` VALUES (9, 50, 7500.00);

3.按着deptid分组,empid排序,去前两行

select empid,deptid,salary,rank from (
select b.empid,b.deptid,b.salary,@rownum:=@rownum+1 ,
if(@pdept=b.deptid,@rank:=@rank+1,@rank:=1) as rank,
@pdept:=b.deptid
from (
select empid,deptid,salary from heyf_t10 order by empid
) b ,(select @rownum :=0 , @pdept := null ,@rank:=0) c ) result
having rank <3;

posted on 2018-01-31 18:50  魂心  阅读(602)  评论(0编辑  收藏  举报