Mysql取分組中前N條記錄


表結構如下:
CREATE TABLE `dwb_rmirror_req_d` (
`thedate` varchar(10) NOT NULL DEFAULT '',
`node` varchar(15) NOT NULL DEFAULT '',
`req_num` bigint(20) DEFAULT NULL,
PRIMARY KEY (`thedate`,`node`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

表中的記錄如下:
mysql> select * from dwb_rmirror_req_d;
+----------+------+------------+
| thedate | node | req_num |
+----------+------+------------+
| 20160215 | f | 2 |
| 20160215 | i | 1 |
| 20160215 | l | 3 |
| 20160217 | f | 2 |
| 20160217 | i | 1 |
| 20160217 | l | 3 |
| 20160218 | f | 2 |
| 20160218 | i | 1 |
| 20160218 | l | 3 |
| 20160219 | f | 2 |
| 20160219 | i | 1 |
| 20160219 | l | 3 |
| 20160220 | f | 2 |
| 20160220 | i | 1 |
| 20160220 | l | 3 |
| 20160221 | f | 2 |
| 20160221 | i | 1 |
| 20160221 | l | 3 |
+----------+------+------------+
18 rows in set (0.00 sec)

1.獲取每天查詢量最大的記錄:
select a.thedate,a.node,a.req_num from dwb_rmirror_req_d a left join dwb_rmirror_req_d b
on a.thedate = b.thedate and a.req_num <= b.req_num
group by a.thedate,a.node,a.req_num
having count(b.node)<=1;
結果如下:
+----------+------+------------+
| thedate | node | req_num |
+----------+------+------------+
| 20160215 | l | 3 |
| 20160217 | l | 3 |
| 20160218 | l | 3 |
| 20160219 | l | 3 |
| 20160220 | l | 3 |
| 20160221 | l | 3 |
+----------+------+------------+
6 rows in set (0.01 sec)

2. 獲取每天查詢量最高的兩條記錄:
select a.thedate,a.node,a.req_num from dwb_rmirror_req_d a left join dwb_rmirror_req_d b
on a.thedate = b.thedate and a.req_num <= b.req_num
group by a.thedate,a.node,a.req_num
having count(b.node)<=2
order by a.thedate,a.req_num;
結果如下:
+----------+------+------------+
| thedate | node | req_num |
+----------+------+------------+
| 20160215 | f | 2 |
| 20160215 | l | 3 |
| 20160217 | f | 2 |
| 20160217 | l | 3 |
| 20160218 | f | 2 |
| 20160218 | l | 3 |
| 20160219 | f | 2 |
| 20160219 | l | 3 |
| 20160220 | f | 2 |
| 20160220 | l | 3 |
| 20160221 | f | 2 |
| 20160221 | l | 3 |
+----------+------+------------+
12 rows in set (0.01 sec)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM