欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

sqlserver分组排序取前三条数据

程序员文章站 2022-03-26 19:48:35
表结构: 方法1: select a.* from Table_Test as a where 3 > (select count(*) from Table_Test where Brand_Id = a.Brand_Id and AddTime > a.AddTime ) order by a. ......

 

 

表结构:sqlserver分组排序取前三条数据

 

 

法1:

  select a.* from table_test as a where 3 > 

    (select count(*) from table_test where brand_id = a.brand_id and addtime > a.addtime )

       order by a.brand_id,a.addtime desc

方法2:

  select * from 

      (select *,row_number() over( partition by brand_id order by addtime desc ) as a from table_test) as c 

      where a<4

运行sql后对应数据:

  sqlserver分组排序取前三条数据