我们有一张数据表,需要按照【类别】分组按照【时间】排序,并分组显示各自的序号。

表Archive

ArchiveId varchar(30) 文章编号非数字
CategoryId int 文章分类Id
StatusId int 状态,-1表示删除,0表示新建,1表示启用
PubTime DateTime 发布时间

 

select top 100 ArchiveId,StatusId,PubTime,CategoryId 
from Archive 
where StatusId>=0
order by PubTime desc

查询结果:

sql-分组排序
按照【类别】分组按照【时间】排序,并分组显示各自的序号。具体做法:
--子表
with asm as(select ArchiveId,StatusId,PubTime,CategoryId from Archive where StatusId>=0)

--查询-------------------
select bb.ArchiveId,bb.StatusId,bb.PubTime,bb.CategoryId,
--序号列生成
   (select COUNT(1) from asm where bb.CategoryId=asm.CategoryId and  bb.PubTime>=asm.PubTime) rowid 
--插入临时表
into #temp  

from Archive bb
where bb.StatusId>=0 

查询临时表:

select top 200 * from #temp  order by CategoryId desc,rowid asc

见查得结果:

sql-分组排序

相关文章:

  • 2021-08-18
  • 2021-12-15
  • 2021-05-28
  • 2021-07-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-09
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-04-06
  • 2021-06-17
  • 2021-05-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案