怎么样实现分组取前N条记录

netschina 2005-03-04 04:26:28
如下表结构:
分类 字段1 字段2 时间
a 121 336 2004-2-3
b 122 335 2004-2-2
c 123 334 2004-2-1
a 124 333 2004-2-2
b 125 332 2004-2-1
c 126 331 2004-2-8
........

要得到分类的最近时间的前几条字段

请大虾多多指教

...全文
203 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
netschina 2005-03-10
  • 打赏
  • 举报
回复
谢谢大家,几位的方法都是正确的,但就是效率都不是很高,请问还有什么更好的方法
上面的表的有唯一的关键字id
lingdian000 2005-03-07
  • 打赏
  • 举报
回复
select * from 表 a
where 字段1 in (select top 10 a.字段1 from 表 b where b.分类=a.分类 order by b.时间)
order by 分类
netschina 2005-03-07
  • 打赏
  • 举报
回复
jiang130(Hong):
你的方法只能得到最新的一条记录,如果是要得到几条记录,应该怎么做?
jiang130 2005-03-07
  • 打赏
  • 举报
回复
經過測試的:

select identity(int,1,1) as rowid,* into #1 from 表 order by 分類,時間
declare @ts int 要取的條數
select a.* from #1 a inner join
(select deptid,min(rowid) as rowid from #1 group by deptid)b
on a.分類=b.分類 and a.rowid-b.rowid between 0 and @ts-1
JackyBeauty 2005-03-07
  • 打赏
  • 举报
回复
再补充一下,如果在表结构加一个自增字段id,那用lsxaa(小李铅笔刀)的方法,把时间字段更改为id,就一定正确了
JackyBeauty 2005-03-07
  • 打赏
  • 举报
回复
希望楼主把条件更明确一点,日期字段是不是唯一的?
JackyBeauty 2005-03-07
  • 打赏
  • 举报
回复
如果时间字段包括毫秒保证是唯一的话, lsxaa(小李铅笔刀) 的基本是正确的,应该也是最简单的
后面要<=前几条
如果时间字段只是日期的话这样就不对了,比如假设第一个日期是2005-02-03,后面两条日期都是
2005-02-02,条件是取两条,下面语句的结果是后两条一个都取不到,实际是应该取一条的
select *
from 表 t
where (select count(*) from 表 where 分类=t.分类 and 时间>=t.时间)<=前几条
jiang130 2005-03-07
  • 打赏
  • 举报
回复
select identity(int,1,1) as rowid,* into #1 from 表 order by 分類
declare @ts int 要取的條數
select a.* from #1 a inner join
(select * from #1)b
on a.分類=b.分類 and b.rowid-a.rowid between 0 and @ts-1
lsxaa 2005-03-07
  • 打赏
  • 举报
回复
select *
from 表 t
where (select count(*) from 表 where 分类=t.分类 and 时间>=t.时间)<前几条
lsxaa 2005-03-07
  • 打赏
  • 举报
回复
select * from 表 t
where (select count(*) from tablename where 分类=t.分类 and 时间>t.时间)>前几条
jiang130 2005-03-04
  • 打赏
  • 举报
回复
select a.* from 表 a inner join
(select 分類﹐max(時間) as 時間 from 表 group by 分類)b
on a.分類=b.分類 and a.時間=b.時間
xluzhong 2005-03-04
  • 打赏
  • 举报
回复
select *
from tablename t
where not exists(select 1 from tablename where 分类=t.分类 and 时间>t.时间)
Softlee81307 2005-03-04
  • 打赏
  • 举报
回复
select top 10 分类,字段1 ,字段2 ,时间 from 表 order 时间 desc
Softlee81307 2005-03-04
  • 打赏
  • 举报
回复
select top 數目 分类,字段1 ,字段2 ,时间 from 表 order 时间 desc

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧