Mysql——分组排序加序列号
2016-04-24 14:26
826 查看
CREATE TABLE IF NOT EXISTS `employee` ( `empid` int(11) DEFAULT NULL, `deptid` int(11) DEFAULT NULL, `salary` decimal(10,2) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; INSERT INTO `employee` (`empid`, `deptid`, `salary`) 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);
<span style="font-family: Monaco, Consolas, Courier, 'Lucida Console', monospace; font-size: 14px; line-height: 21px; white-space: pre; widows: auto;">是这样的我想实现新加一列代表每个部门的工资等级,比如</span><pre name="code" class="sql">+-------+--------+----------+ | empid | deptid | salary | +-------+--------+----------+ | 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 | +-------+--------+----------+ //实现下面结果 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 *,@rownum:=@rownum+1 AS rownum,IF(@pa=ff.deptid,@rank:=@rank+1,@rank:=1) AS rank,@pa:=ff.deptid FROM (SELECT empid,deptid,salary FROM employee GROUP BY deptid,salary ORDER BY deptid ASC, salary DESC) ff,(SELECT @rank:=0,@rownum:=0,@pa=NULL) tt) result
相关文章推荐
- [笔记]在Mac下进行mysql操作细节
- Mysql批量删除和修改某个前缀的表
- MySQL排错工具perror
- MySQL排错工具perror
- MySQL datetime数据类型设置当前时间为默认值
- HIVE+mysql环境搭建及简单应用
- mysql 时间
- 查看修改mysql编码方式
- mysql死锁,等待资源,事务锁,Lock wait timeout exceeded; try restarting transaction解决
- 绿色版mysql
- mysql处理海量数据时的一些优化查询速度方法
- MySQL已有column值为NULL,修改列属性为NOT NULL报1138错误
- MySQL常用函数
- jsp连接mysql数据库
- Mysql远程链接访问权限设置
- mysql 加了 skip-name-resolve不能链接数据库问题的解决方法
- Mysql:常用代码
- MySQL查询优化
- 用脚本完成mysql工作
- mysqlbinlog的使用