oracle里面要获取每个分组里面的topN可以采用:
select *
from (select emp_id, name, occupation,
rank() over ( partition by occupation order by emp_id) rank
from employee)
where rank <= 3
select * from
(select emp_id, name, occupation,rank() over (
partition by occupation order by emp_id,RowNum) rank
from employee)
where rank <= 3
mysql:分组之后取topN的sql:
Here’s another form of the solution without subquery that also resolves matching ratings by using the primary key:
DROP DATABASE IF EXISTS topn;
CREATE DATABASE topn;
USE topn;
CREATE TABLE theTable (
pKey int PRIMARY KEY
, groupId int
, rating int
);
INSERT INTO theTable (
pKey
, groupId
, rating
) VALUES
( 1, 1, 55 )
, ( 2, 1, 53 )
, ( 3, 1, 51 )
, ( 4, 1, 59 )
, ( 5, 1, 58 )
, ( 6, 1, 58 )
, ( 7, 1, 53 )
, ( 8, 1, 55 )
, ( 9, 1, 55 )
, ( 10, 1, 53 )
, ( 11, 2, 52 )
, ( 12, 2, 53 )
, ( 13, 2, 54 )
, ( 14, 2, 59 )
, ( 15, 2, 58 )
, ( 16, 2, 57 )
, ( 17, 2, 56 )
;
SELECT t1.pKey
, t1.rating
, t1.groupId
, COUNT(t2.pKey) AS cnt
FROM theTable AS t1
LEFT JOIN theTable AS t2
ON (t1.rating, t1.pKey) <= (t2.rating, t2.pKey)
AND t1.groupId = t2.groupId
GROUP BY t1.pKey
, t1.rating
, t1.groupId
HAVING cnt <= 5
ORDER BY t1.groupId, cnt
;
查询结果:
参考:http://www.blogjava.net/pengpenglin/archive/2008/06/27/211019.html
http://thenoyes.com/littlenoise/?p=36

- 大小: 48.3 KB
分享到:
相关推荐
你可以利用PHP连接包括Oracle,MS-Access,Mysql在内的大部分数据库。你可以在苍蝇上画图,编写程序下载或者显示e-mail。你甚至可以完成网络相关的功能。最好的是,你可以选择你的PHP安装版本需要哪些功能。引用...
实际应用中可能还需要考虑其他类型的数据库如MySQL、Oracle等,并相应地调整连接字符串和驱动。 ##### 3. 结果集处理 这部分代码主要负责处理查询结果,并计算总页数以及当前页的数据范围。 ```jsp int i = 1; ...
程序基于 JSP + JavaBean 开发,数据库可以使用Access,MySql,MSSQL,Oracle数据库。 开发平台:Win2003 + Apache2.0.52 + Tomcat5.54 + Mod_jk 1.2.6 + JDK1.5 程序正常运行需要JVM(Java虚拟机)1.5以上的版本。 ...
button will open CurrPorts. (Without this option, double-click is required) * Version 1.75: o Added 'Exclude Selected Processes In Filters' option in the context menu. o Added accelerator key ...
It is handy in studying database programming.<END><br>20 , MySQLExplorer.zip Explorer for MySQL Data Base.You can retrieve and execute your query. <END><br>21 , ICDBaseSource115.zip DAO based ...
第29章 人员信息管理项目 (接口设计模式+MySQL数据库) 29.1 人员信息管理原理 29.1.1 项目结构框架分析 29.1.2 项目功能业务分析 29.2 人员信息管理项目前期准备 29.2.1 设计数据库 29.2.2 数据库操作相关类 29.3 ...