设为首页收藏本站Access中国

Office中国论坛/Access中国论坛

 找回密码
 注册

QQ登录

只需一步,快速开始

返回列表 发新帖
查看: 5542|回复: 8

[查询] 先分组,再取每组前3名,如何实现呢

[复制链接]
发表于 2016-2-19 16:11:16 来自手机 | 显示全部楼层 |阅读模式
先分组,再取每组前3名,如何实现呢
来自: 微社区

点击这里给我发消息

发表于 2016-2-19 16:31:28 | 显示全部楼层
select top 3 字段  from 表 group by 字段
试试
 楼主| 发表于 2016-2-19 17:13:36 来自手机 | 显示全部楼层
这样取不了每组前3,取的是总体前3
来自: 微社区
发表于 2016-2-20 09:26:38 | 显示全部楼层
看看你的数据
发表于 2016-2-22 08:55:28 | 显示全部楼层
select  字段  from 表 group by 字段查询
select  top 3 字段  from查询 group by 字段
发表于 2016-2-23 08:07:49 | 显示全部楼层
用SQL语句的方式呢,在ACCESS只能用Count计数嵌套子查询后,再来通过Where 来判断Count的大小来取数据,数据量小时还凑合,
如:  

按name分组取最小的两个(N个)val

代码如下:

select a.* from tb a where 2 > (select count(*) from tb where name = a.name and val < a.val ) order by a.name,a.valselect a.* from tb a where val in (select top 2 val from tb where name=a.name order by val) order by a.name,a.val
select a.* from tb a where exists (select count(*) from tb where name = a.name and val < a.val having Count(*) < 2) order by a.name      ----网上抄的。。

如果是MSSQL呢,有个row_number的函数(排序行号),对这个就是大小判断就行了。效率最好

另一种方式是用游标方式,因为MSSQL有自身的游标,所以效果仅次于row_number,ACCESS的话用ADO或DAO游标,方法比较简单些,只是要写一定的VBA代码

这个题看起来简单,做起来,很多的人会想到 Top +group by 的方式,相关贴呢,自已问度娘。这里就不贴地址了。
 楼主| 发表于 2016-2-23 09:40:52 来自手机 | 显示全部楼层
用子查询和ado实现效率比较低,目前好像却也没有更好的办法了
来自: 微社区
发表于 2016-2-23 11:15:31 | 显示全部楼层
本帖最后由 roych 于 2016-2-23 11:17 编辑

1、使用联合查询:
select top 3 字段 from 表
where xx=a
union
select top 3 字段 from 表
where xx=b
…………………………
select top 3 字段 from 表
where xx=n

2、创建一列,更新为序列号,再处理:
数据定义查询:alter 表 add Column 序号 long;
更新查询:Update 表 set 序号=Dcount("字段","表","字段="&[字段]);
选择查询:select * from 表 where 序号<=3;

3、ADO处理。分别创建2个记录集,一个为分组字段,另一个则以分组字段为条件。通过movenext的方法来完成第二个记录集的读取。
rst1.open "select distinct 字段 from 表",currentproject.connection,adOpenKeyset, adLockOptimistic
do until rst1.eof
rst2.open"select * from b "& where 字段='"& rst1(0)&"' order by 某字段",currentproject.connection,adOpenKeyset,adLockOptimistic
for i=1 to 3

xx=rst2(0)
………………
rst2.movenext
next
rsst2.close
rst1.movenext
loop
…………………………
个人推荐使用方法2
 楼主| 发表于 2016-2-26 12:24:30 | 显示全部楼层
很全面,非常感谢
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|站长邮箱|小黑屋|手机版|Office中国/Access中国 ( 粤ICP备10043721号-1 )  

GMT+8, 2024-3-29 00:26 , Processed in 0.115525 second(s), 33 queries .

Powered by Discuz! X3.3

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表