SQL Server 获取每组中的前N个

方法一:

--建立测试环境 
create table ta3(id varchar(4),repairvalue numeric(4,2),pieceid varchar(2),facid varchar(8)) 
insert into ta3 
select '01',4.6,'1','aaa' 
union all select '02',2,'1','aaa' 
union all select '03',0,'1','aaa' 
union all select '04',3,'1','aaa' 
union all select '05',5,'1','aaa' 
union all select '06',4.6,'2','aaa' 
union all select '07',7.8,'2','aaa' 
union all select '08',0,'2','aaa' 
union all select '09',5,'2','aaa' 
union all select '10',3,'2','aaa' 
--测试 
Select id,repairvalue,pieceid from ta3 A 
Where Not Exists(Select 1 from ta3 Where pieceid=A.pieceid And repairvalue>A.repairvalue Having Count(1)>2) --这里N取3
Order By pieceid,repairvalue Desc 
--删除测试环境 
Drop Table ta3 
--结果 
/* 
id repairvalue pieceid 
05 5.00 1 
01 4.60 1 
04 3.00 1 
07 7.80 2 
09 5.00 2 
06 4.60 2 
*/ 

方法二:





if object_id('tb') is not null
   drop table tb
go


create table tb
([id] int, [title] numeric(12,1), [typeid] int, [datetime] int)


insert into tb
select 1,1.1,1,1
union all select 2,1.2,1,2
union all select 3,1.3,1,3
union all select 4,2.1,2,4
union all select 5,2.2,2,5
union all select 6,2.3,2,6
union all select 7,3.1,3,7
union all select 8,3.2,3,8
union all select 9,3.3,3,9


select *
from
(
select *,
       
       --先按typeid分组,在一组中按照datetime降序排列,来编号
       ROW_NUMBER() over(partition by typeid 
                             order by datetime desc)  as rownum
from tb
)t
where rownum<=2  --取行号为1和2的,也就是时间最大的2条数据


/*
id<span style="white-space:pre">	</span>title<span style="white-space:pre">	</span>typeid<span style="white-space:pre">	</span>datetime<span style="white-space:pre">	</span>rownum
3<span style="white-space:pre">	</span>1.3<span style="white-space:pre">	</span>1<span style="white-space:pre">	</span>3<span style="white-space:pre">	</span>1
2<span style="white-space:pre">	</span>1.2<span style="white-space:pre">	</span>1<span style="white-space:pre">	</span>2<span style="white-space:pre">	</span>2
6<span style="white-space:pre">	</span>2.3<span style="white-space:pre">	</span>2<span style="white-space:pre">	</span>6<span style="white-space:pre">	</span>1
5<span style="white-space:pre">	</span>2.2<span style="white-space:pre">	</span>2<span style="white-space:pre">	</span>5<span style="white-space:pre">	</span>2
9<span style="white-space:pre">	</span>3.3<span style="white-space:pre">	</span>3<span style="white-space:pre">	</span>9<span style="white-space:pre">	</span>1
8<span style="white-space:pre">	</span>3.2<span style="white-space:pre">	</span>3<span style="white-space:pre">	</span>8<span style="white-space:pre">	</span>2
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值