MySQL分组排序取前N条记录 以及 生成自动数字序列 的SQL

-- MySQL分组排序取前N条记录的最简洁的单条sql。


USE test;


DROP TABLE IF EXISTS test;


CREATE TABLE test (
id INT PRIMARY KEY,
cid INT,
author VARCHAR(30)
) ENGINE=MYISAM;


INSERT INTO test VALUES
(1,1,'test1'),
(2,1,'test1'),
(3,1,'test2'),
(4,1,'test2'),
(5,1,'test2'),
(6,1,'test3'),
(7,1,'test3'),
(8,1,'test3'),
(9,1,'test3'),
(10,2,'test11'),
(11,2,'test11'),
(12,2,'test22'),
(13,2,'test22'),
(14,2,'test22'),
(15,2,'test33'),
(16,2,'test33'),
(17,2,'test33'),
(18,2,'test33');


INSERT INTO test VALUES (200,200,'200test_nagios');




SELECT * FROM (SELECT cid,author,COUNT(*) AS number FROM test GROUP BY cid,author) a
WHERE
N>(
SELECT COUNT(*)
FROM (SELECT cid,author,COUNT(*) AS number FROM test GROUP BY cid,author) b
WHERE a.cid=b.cid AND a.number<b.number
)ORDER BY cid,number DESC;


结果如下:

mysql> SELECT * FROM (SELECT cid,author,COUNT(*) AS number FROM test GROUP BY cid,author) a 
    -> WHERE  
    -> 3>(
    ->     SELECT COUNT(*) 
    ->     FROM (SELECT cid,author,COUNT(*) AS number FROM test GROUP BY cid,author) b
    ->     WHERE a.cid=b.cid AND a.number<b.number
    -> )ORDER BY cid,number DESC;
+------+----------------+--------+
| cid  | author         | number |
+------+----------------+--------+
|    1 | test3          |      4 |
|    1 | test2          |      3 |
|    1 | test1          |      2 |
|    2 | test33         |      4 |
|    2 | test22         |      3 |
|    2 | test11         |      2 |
|  200 | 200test_nagios |      1 |
+------+----------------+--------+
7 rows in set (0.00 sec)


N就是取分组之后的最前面几个判断,N=3就是取前3个





-- 生成自动数字序列
SET @ROW=0;
SELECT a.*,(@ROW:=@ROW +1)Rank
FROM test a;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值