group top n, 可以同时用吗?

haochin 2012-09-14 11:19:32
sql server 2000
col0 col1 col2
1 a 1
2 a 2
4 a 3
5 c 1
6 c 2
7 c 3
8 b 1
9 b 2

得到
以col1分组。找出每组中col2值最小的前两条记录

可以用group top n同时?
...全文
117 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
DBA_磊仔 2012-09-15
  • 打赏
  • 举报
回复
没有这样的语法,但是可以用其他方式实现这一逻辑
叶子 2012-09-15
  • 打赏
  • 举报
回复
没有group by top n的写法
以学习为目的 2012-09-15
  • 打赏
  • 举报
回复
[Quote=引用楼主 的回复:]
sql server 2000
col0 col1 col2
1 a 1
2 a 2
4 a 3
5 c 1
6 c 2
7 c 3
8 b 1
9 b 2

得到
以col1分组。找出每组中col2值最小的前两条记录

……
[/Quote]
sql 2000的,用1楼的写法吧。
發糞塗牆 2012-09-15
  • 打赏
  • 举报
回复
没有group by top n的写法,由于是2000,row_number也不能用,还是使用top来实现吧
以学习为目的 2012-09-14
  • 打赏
  • 举报
回复
select * from (select *,rn=row_number()over(partition by  col1 order by col2)a where  rn  in(1,2)  
百年树人 2012-09-14
  • 打赏
  • 举报
回复
--或者
select * from tb t
where (select count(1) from tb where col1=t.col1 and col2<=t.col2)<=2
百年树人 2012-09-14
  • 打赏
  • 举报
回复
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([col0] int,[col1] varchar(1),[col2] int)
insert [tb]
select 1,'a',1 union all
select 2,'a',2 union all
select 4,'a',3 union all
select 5,'c',1 union all
select 6,'c',2 union all
select 7,'c',3 union all
select 8,'b',1 union all
select 9,'b',2
go

select * from tb t
where col2 in(select top 2 col2 from tb where col1=t.col1 order by col2 asc)

/**
col0 col1 col2
----------- ---- -----------
1 a 1
2 a 2
5 c 1
6 c 2
8 b 1
9 b 2

(6 行受影响)
**/

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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