最新消息: 新版网站上线了!!!

mysql 分组 组内排序 取每组前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);   
SQL语句如下:
1. SELECT a.* FROM `heyf_t10` a WHERE (SELECT COUNT(*) FROM `heyf_t10` WHERE `deptid`=a.`deptid` AND `salary`>a.`salary`) < 2 ORDER BY a.`deptid`, a.`salary` DESC;
 SELECT a.*,b.* FROM heyf_t10 a, heyf_t10 b WHERE a.`deptid`=b.`deptid` AND a.`salary`<=b.`salary` GROUP BY a.`deptid`, a.`salary`  HAVING COUNT(a.`deptid`)<=2;
测试结果查看:
SELECT a.*,(SELECT COUNT(*) FROM `heyf_t10` WHERE `deptid`=a.`deptid` AND `salary`>a.`salary`) AS total FROM `heyf_t10` a  ORDER BY a.`deptid`, a.`salary` DESC;
SELECT a.*,b.*, COUNT(a.`deptid`) FROM heyf_t10 a, heyf_t10 b WHERE a.`deptid`=b.`deptid` AND a.`salary`<=b.`salary` GROUP BY a.`deptid`, a.`salary`;
.....

转载请注明:谷谷点程序 » mysql 分组 组内排序 取每组前2条数据